1. 程式人生 > >java實現分頁技術詳解

java實現分頁技術詳解

1.編寫通用的分頁工具

public class PageUtil {
	
	/*引數需要頁面傳入*/
	private Integer pageSize=10;//每頁顯式多少條記錄
	private Integer currentPage=1;//當前頁號
	
	/*引數需要從資料查詢*/
	private Integer allRowsAmount=0;//總記錄數
	private List<?> items;//記錄集合
	
	/*這些引數由計算得出*/
	private Integer allPageAmount;//總頁數
	private Integer currentPageStartRow=1;//當前頁面的開始行
	private Integer currentPageEndRow;//當前頁面的結束行
	private Integer firstPage=1;//首頁的頁號
	private Integer lastPage;//末頁的頁號
	private Integer prevPage;//上一頁頁號
	private Integer nextPage;//下一頁頁號
	private Integer startPageNum;//導航開始頁號
	private Integer endPageNum;//導航結束頁號
	private Integer maxPageAmount =10;//最多顯示多少頁
	public List<Integer> showPageNums =new ArrayList<Integer>();//要顯示的頁號
	
	public PageUtil() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	/*設定當前頁*/
	public void setCurrentPage(int currentPage){
		if(currentPage <1){
			this.currentPage=1;
		}else{
			this.currentPage=currentPage;
		}
	}
	/*設定每頁記錄數,預設10條*/
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	/*設定總記錄數*/
	public void setAllRowsAmount(int allRowsAmount) {
		this.allRowsAmount = allRowsAmount;
	}
	/*設定分頁內容*/
	public void setItems(List<?> items) {
		this.items = items;
	}
	/*設定導航頁數量*/
	public void setMaxPageAmount(int maxPageAmount) {
		this.maxPageAmount = maxPageAmount;
	}
	
	public void calculatePage(){
		//計算總頁數
		if(this.allRowsAmount % this.pageSize ==0){
			this.allPageAmount=this.allRowsAmount/this.pageSize;
		}else{
			this.allPageAmount=this.allRowsAmount/this.pageSize+1;
		}
		//設定首頁
		this.firstPage=1;
		//設定末頁
		this.lastPage=this.allPageAmount;
		if(this.currentPage *pageSize <allRowsAmount){
			this.currentPageEndRow =this.currentPage*pageSize;
			this.currentPageStartRow =(this.currentPage-1)*pageSize+1;
		}else{
			this.currentPageEndRow =this.allRowsAmount;
			this.currentPageStartRow =(this.allPageAmount-1)*pageSize+1;
			if(this.currentPageStartRow <0){
				this.currentPageStartRow=0;
			}
		}
		//設定前一頁
		if(this.currentPage >1){
			this.prevPage=this.currentPage-1;
		}else{
			this.prevPage=this.currentPage;
		}
		//設定下一頁
		if(this.currentPage <this.lastPage){
			this.nextPage=this.currentPage+1;
		}else{
			this.nextPage=this.lastPage;
		}
		//計算數字導航頁
		startPageNum =Math.max(this.currentPage-maxPageAmount/2, firstPage);
		endPageNum =Math.min(startPageNum+maxPageAmount, lastPage);
		if(endPageNum-startPageNum <maxPageAmount){
			startPageNum =Math.max(endPageNum -maxPageAmount , 1);
		}
		for(int i=startPageNum ;i<=endPageNum;i++){
			showPageNums.add(i);
		}
	}
	
	//以下get方法是對外提供的方法用來獲取引數值
	public Integer getPageSize() {
		return pageSize;
	}

	public Integer getCurrentPage() {
		return currentPage;
	}

	public Integer getAllRowsAmount() {
		return allRowsAmount;
	}

	public List<?> getItems() {
		return items;
	}

	public Integer getAllPageAmount() {
		return allPageAmount;
	}

	public Integer getCurrentPageStartRow() {
		return currentPageStartRow;
	}

	public Integer getCurrentPageEndRow() {
		return currentPageEndRow;
	}

	public Integer getFirstPage() {
		return firstPage;
	}

	public Integer getLastPage() {
		return lastPage;
	}

	public Integer getPrevPage() {
		return prevPage;
	}

	public Integer getNextPage() {
		return nextPage;
	}

	public Integer getStartPageNum() {
		return startPageNum;
	}

	public Integer getEndPageNum() {
		return endPageNum;
	}

	public Integer getMaxPageAmount() {
		return maxPageAmount;
	}

	public List<Integer> getShowPageNums() {
		return showPageNums;
	}

	@Override
	public String toString() {
		return "PageUtil [pageSize=" + pageSize + ", currentPage="
				+ currentPage + ", allRowsAmount=" + allRowsAmount + ", 每頁內容items="
				+ items + ", allPageAmount=" + allPageAmount
				+ ", currentPageStartRow=" + currentPageStartRow
				+ ", currentPageEndRow=" + currentPageEndRow + ", firstPage="
				+ firstPage + ", lastPage=" + lastPage + ", prevPage="
				+ prevPage + ", nextPage=" + nextPage + ", startPageNum="
				+ startPageNum + ", endPageNum=" + endPageNum + ", maxPageAmount="
				+ maxPageAmount + ", 頁號list=" + showPageNums + "]";
	}
	
	public static void main(String[] args) {
		List<String> items =new ArrayList<String>();
		for(int i=0;i<10;i++){
			items.add("str"+i);
		}
		PageUtil pageUtil =new PageUtil();
		pageUtil.setCurrentPage(1);
		//pageUtil.setItems(items);
		pageUtil.setAllRowsAmount(33);
		pageUtil.calculatePage();
		System.out.println(pageUtil);
	}
}

2.servlet+c3p0+mysql實現分頁

工程目錄:


環境搭建:

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.2.1</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.22</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
</dependencies>

c3p0配置檔案:

<c3p0-config>
	<!-- 預設配置 -->
  <default-config>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property>
    <property name="driverClass">com.mysql.jdbc.Driver</property> 
    <property name="user">root</property> 
    <property name="password"></property> 
    <property name="initialPoolSize">3</property>
    <property name="maxPoolSize">6</property>
    <property name="maxIdleTime">1000</property>
  </default-config>
  <!-- 以下的配置用於個人需要再配置 -->
  <name-config name="my_config">
  	<property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property>
    <property name="driverClass">com.mysql.jdbc.Driver</property> 
    <property name="user">root</property> 
    <property name="password"></property> 
    <property name="initialPoolSize">3</property>
    <property name="maxPoolSize">6</property>
    <property name="maxIdleTime">1000</property>
  </name-config>
</c3p0-config>

使用c3p0連線池的工具類:

public class DbUtil {
	
	 private static DataSource dataSource=null;  
	 static{  
		 dataSource=new ComboPooledDataSource();  
	 }  
	      
	 public static Connection getConnection(){  
	     try{  
	    	 return dataSource.getConnection();  
	     }catch(SQLException e){  
	         throw new RuntimeException(e);  
	     }  
	 }  
	      
	 //釋放物件的連線  
	 public static void close(Connection conn,Statement stmt,ResultSet rs){  
	     if(rs !=null){  
	          try{  
	        	  rs.close();  
	          }catch(SQLException e){  
	              e.printStackTrace();  
	              throw new RuntimeException(e);  
	          }  
	     }  
	     if(stmt !=null){  
	          try{  
	              stmt.close();  
	          }catch(SQLException e){  
	              e.printStackTrace();  
	              throw new RuntimeException(e);  
	          }  
	        }     
	     if(conn !=null){  
	          try{  
	              conn.close();  
	          }catch(SQLException e){  
	              e.printStackTrace();  
	              throw new RuntimeException(e);  
	          }  
	     }  
	 }
	 public static void main(String[] args) throws Exception{
		 String sql="select id,username,gender from myuser limit 3,10";
		 Connection conn =DbUtil.getConnection();
		 PreparedStatement ps =conn.prepareStatement(sql);
		 ResultSet rs =ps.executeQuery();
		 while(rs.next()){
			 String id =rs.getString("id");
			 String username =rs.getString("username");
			 String gender =rs.getString("gender");
			 System.out.println(id+","+username+","+gender);
		 }
		 DbUtil.close(conn,ps,rs);
	 }
}

dao層:主要是獲取記錄的總數便於計算其他值,還有就是獲取每頁顯示的資料。

public class UserDaoImpl implements IUserDao{
	
	//從資料庫查詢記錄的總條數
	public Integer getAllRowsAmount() throws Exception{
		String sql="select count(*) from myuser";
		Connection conn =DbUtil.getConnection();
		PreparedStatement pstmt =conn.prepareStatement(sql);
		ResultSet rs =pstmt.executeQuery();
		Integer allRowsAmount=0;
		if(rs.next()){
			allRowsAmount =rs.getInt("count(*)");
		}
		DbUtil.close(conn, pstmt, rs);
		return allRowsAmount;
	}
	
	//通過當前頁號查詢條件記錄
	public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception{
		String sql="select id,username,gender from myuser limit "+(currentPageStartRow-1)+","+pageSize;
		Connection conn =DbUtil.getConnection();
		PreparedStatement pstmt =conn.prepareStatement(sql);
		ResultSet rs =pstmt.executeQuery();
		List<User> list =new ArrayList<User>();
		while(rs.next()){
			User user =new User();
			user.setId(rs.getInt("id"));
			user.setUsername(rs.getString("username"));
			user.setGender(rs.getString("gender"));
			list.add(user);
		}
		DbUtil.close(conn, pstmt, rs);
		return list;
	}
	public static void main(String[] args) throws Exception {
		UserDaoImpl userDaoImpl =new UserDaoImpl();
		PageUtil pageUtil =new PageUtil();
		pageUtil.setAllRowsAmount(userDaoImpl.getAllRowsAmount());
		pageUtil.calculatePage();
		for(User user :userDaoImpl.getUserByCurrentPage(pageUtil.getStartPageNum(), pageUtil.getPageSize())){
			System.out.println(user.getId()+","+user.getUsername()+","+user.getGender());
		}
		System.out.println(userDaoImpl.getAllRowsAmount());
	}
}
dao介面:
public interface IUserDao {

	public Integer getAllRowsAmount() throws Exception;
	
	public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception;
}

model類:

User.java:

public class User {
	private int id;
	private String username;
	private String gender;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
}
頁面顯示的模型Page.java:
public class Page {
	private Integer currentPage;
	private Integer prevPage;
	private Integer nextPage;
	private List<User> showUsers =new ArrayList<User>();
	private List<Integer> showPageNums =new ArrayList<Integer>();
	public Integer getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(Integer currentPage) {
		this.currentPage = currentPage;
	}
	public Integer getPrevPage() {
		return prevPage;
	}
	public void setPrevPage(Integer prevPage) {
		this.prevPage = prevPage;
	}
	public Integer getNextPage() {
		return nextPage;
	}
	public void setNextPage(Integer nextPage) {
		this.nextPage = nextPage;
	}
	public List<User> getShowUsers() {
		return showUsers;
	}
	public void setShowUsers(List<User> showUsers) {
		this.showUsers = showUsers;
	}
	public List<Integer> getShowPageNums() {
		return showPageNums;
	}
	public void setShowPageNums(List<Integer> showPageNums) {
		this.showPageNums = showPageNums;
	}
}

service層:通過頁面傳入當前頁號資料,來查詢需要的值。

UserService.java:

public class UserServiceImpl implements IUserService{
	
	private IUserDao userDao =new UserDaoImpl();
	
	public Page pageUsers(String currentPage) throws Exception{
		int allRowsAmount =userDao.getAllRowsAmount();
		PageUtil pageUtil =new PageUtil();
		pageUtil.setAllRowsAmount(allRowsAmount);
		if(currentPage !=null){
			pageUtil.setCurrentPage(Integer.parseInt(currentPage));
		}
		pageUtil.calculatePage();
		List<User> list =userDao.getUserByCurrentPage(pageUtil.getCurrentPageStartRow(), pageUtil.getPageSize());
		Page page =new Page();
		page.setPrevPage(pageUtil.getPrevPage());
		page.setNextPage(pageUtil.getNextPage());
		page.setShowUsers(list);
		page.setShowPageNums(pageUtil.getShowPageNums());
		page.setCurrentPage(pageUtil.getCurrentPage());
		return page;
	}
}
Service介面:
public interface IUserService {
	public Page pageUsers(String currentPage) throws Exception;
}

Controller層:

public class UserController extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private IUserService userService =new UserServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String currentPage =req.getParameter("currentPage");
		Page page =null;
		try {
			page =userService.pageUsers(currentPage);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		req.setAttribute("page", page);	
		req.getRequestDispatcher("/page.jsp").forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doPost(req, resp);
	}
	
}

匯入jquery的js檔案:


Page.jsp檔案:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-2.1.3.js"></script>
<script type="text/javascript" src="js/jquery-2.1.3.min.js"></script>
<title>分頁</title>
<style type="text/css">
	a{
		font-size:14px;
		text-decoration:none;
	}
	td{
		text-align:center;
	}
	#prevPage{
		padding:6px;
		color:blue;
		width:24px;
		height:24px;
		border:1px solid #ccc;
	}
	#pageNum{
		padding-top:6px;
		padding-left:12px;
		color:blue;
		border:1px solid #ccc;
		padding-right:12px;
		padding-bottom:6px;
	}
	#nextPage{
		padding:6px;
		color:blue;
		width:24px;
		height:24px;
		border:1px solid #ccc;
	}
</style>
</head>
<body>
	<div class="container" id="pagenation" align="center">
    	<table border="1" width="80%" cellpadding="5" cellspacing="0">
    		<tr>
	  			<th>序號</th>
	  			<th>使用者名稱</th>
	  			<th>性別</th>
  			</tr>
  			<c:forEach items="${page.showUsers}" var="user">
	            <tr>
	                <td>${user.id}</td>
	                <td>${user.username}</td>
	                <td>${user.gender}</td>
	            </tr>
        	</c:forEach>
    	</table>
	</div>
	<div>
		<c:when test="${page.currentPage==1}">
			<上一頁
		</c:when>
		<c:otherwise>
			<a href="http://localhost:8080/paging/user.htm?currentPage=${page.prevPage}" id="prevPage"><上一頁</a>
		</c:otherwise>
        <c:forEach items="${page.showPageNums}" var="pageNum">
            <a href="http://localhost:8080/paging/user.htm?currentPage=${pageNum}" id="pageNum">${pageNum}</a>
        </c:forEach>
        <a href="http://localhost:8080/paging/user.htm?currentPage=${page.nextPage}" id="nextPage">下一頁></a>
	</div>
</body>
<script type="text/javascript">
	$(function(){
		$("#prevPage").mousemove(function(){
			$("#prevPage").css("border-color","#4a86e8");
			$("#prevPage").css("background","#d5dce8");
		});
		$("#prevPage").mouseout(function(){
			$("#prevPage").css("border-color","#ccc");
			$("#prevPage").css("background","white");
		});
		$("#nextPage").mousemove(function(){
			$("#nextPage").css("border-color","#4a86e8");
			$("#nextPage").css("background","#d5dce8");
		});
		$("#nextPage").mouseout(function(){
			$("#nextPage").css("border-color","#ccc");
			$("#nextPage").css("background","white");
		});
		
	});
</script>
</html>
結果: