日期:2014-05-16  浏览次数:20335 次

jsp中实现分页查询




1.确定数据的数量,示例如下:

public int getTotalCount() {
		// TODO Auto-generated method stub
		int totalCount=0;
		String sql="select count(*) from news_detail";
		Object[] params={};
		ResultSet rs=this.executeSQL(sql, params);
		try {
			while(rs.next()){
				totalCount=rs.getInt(1);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//释放资源
			this.closeResource();
		}
		return totalCount;
	}


2.确定显示的页数,示例:

private void setTotalPageCountByRs(){
		if(this.recordCount%this.pageSize==0){
			this.totalPageCount=this.recordCount/this.pageSize;
		}else if(this.recordCount%this.pageSize>0){
			this.totalPageCount=this.recordCount/this.pageSize+1;
		}else
			this.totalPageCount=0;
	}

3.实现分页获取信息

public List<News> getPageNewsList(int pageNo, int pageSize) {
		// TODO Auto-generated method stub
		List<News> newsList=new ArrayList<News>();
		String sql="SELECT id,title,author,createdate FROM (SELECT id,title,author,createdate,ROWNUM rn FROM news_detail) a WHERE a.rn>=? AND a.rn<=?";
		Page page=new Page();
		page.setCurrentPageNo(pageNo);//设置当前页码
		page.setPageSize(pageSize);//每页显示记录数
		//计算sql语句的起始记录数以及结束记录数的行数
		int startRow=page.getStartRow();
		int endRow=page.getEndRow();
		Object[] params={startRow,endRow};
		ResultSet rs=this.executeSQL(sql, params);
		try {
			while(rs.next()){
				int id=rs.getInt("id");
				String title=rs.getString("title");
				String author=rs.getString("author");
				Date date=rs.getDate("createdate");
				News newInfo=new News();
				newInfo.setId(id);
				newInfo.setTitle(title);
				newInfo.setAuthor(author);
				newInfo.setCreateDate(new java.sql.Timestamp(date.getTime()));
			
				newsList.add(newInfo);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			this.closeResource();
		}
		return newsList;
		
		
		
	}