1. 程式人生 > >JavaWeb中的分頁技術

JavaWeb中的分頁技術

前段時間學習SSH框架用到分頁知識,為此還回顧了一下之前JavaWeb中的分頁技術

首先我們先建立一個庫和表用來展示分頁結果

create table Employee(
empId int(11) NOT NULL AUTO_INCREMENT primary key,
empName varchar(20) NOT NULL,
dept_id int(20) NOT NULL
);
insert into Employee(empName,dept_id) values('aa',1);
接下來我用c3p0連線池來連線資料庫

首先我們準備c3p0-config.xml的配置(在ComboPooledDataSource()初始c3p0連線池會載入這裡面的配置資訊,連線具體的資料庫物件)

<c3p0-config>
	<default-config>
		<property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_demo
		</property>
		<property name="driverClass">com.mysql.jdbc.Driver</property>
		<property name="user">root</property>
		<property name="password">123456</property>
		<property name="initialPoolSize">3</property>
		<property name="maxPoolSize">6</property>
		<property name="maxIdleTime">1000</property>
	</default-config>
接下來寫一個連線資料庫的工具類,完成

1.初始化資料庫

2.建立DbUtils核心工具類物件QueryRunner

package cn.itcast.utils;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;

/**
 * 工具類
 * 1. 初始化C3P0連線池
 * 2. 建立DbUtils核心工具類物件
 * @author Jie.Yuan
 *
 */
public class JdbcUtils {

	/**
	 *  1. 初始化C3P0連線池
	 */
	private static  DataSource dataSource;
	static {
		dataSource = new ComboPooledDataSource();
	}
	
	/**
	 * 2. 建立DbUtils核心工具類物件
	 */
	public static QueryRunner getQueryRuner(){
		// 建立QueryRunner物件,傳入連線池物件
		// 在建立QueryRunner物件的時候,如果傳入了資料來源物件;
		// 那麼在使用QueryRunner物件方法的時候,就不需要傳入連線物件;
		// 會自動從資料來源中獲取連線(不用關閉連線)
		return new QueryRunner(dataSource);
	}
}









接下來準備實體類,注意由於要用到DbUtils元件,所以實體類中的屬性要與資料庫的欄位一樣

public class Employee {

	private int empId;			// 員工id
	private String empName;		// 員工名稱
	private int dept_id;		// 部門id
	
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public String getEmpName() {
		return empName;
	}
	public void setEmpName(String empName) {
		this.empName = empName;
	}
	public int getDept_id() {
		return dept_id;
	}
	public void setDept_id(int deptId) {
		dept_id = deptId;
	}
	
	
}
接下來寫分頁的工具類,這個類中包含五個屬性:當前頁,總記錄數,總頁數,每頁的行數,每次查詢的
資料

public class PageBean<T> {
	private int currentPage = 1; // 當前頁, 預設顯示第一頁
	private int pageCount = 4;   // 每頁顯示的行數(查詢返回的行數), 預設每頁顯示4行
	private int totalCount;      // 總記錄數
	private int totalPage;       // 總頁數 = 總記錄數 / 每頁顯示的行數  (+ 1)
	private List<T> pageData;       // 分頁查詢到的資料
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getPageCount() {
		return pageCount;
	}
	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}
	public int getTotalCount() {
		return totalCount;
	}
	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getTotalPage() {
		if(totalCount%pageCount==0){
			this.totalCount=totalCount%pageCount;
		}else{
			this.totalCount=totalCount%pageCount+1;
		}
		return totalPage;
	}
	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}
	public List<T> getPageData() {
		return pageData;
	}
	public void setPageData(List<T> pageData) {
		this.pageData = pageData;
	}
	

}
接下來我們準備dao,前面我們在分頁類中還需要獲得總記錄數和查詢到的資料

public interface UserDao {
public int getTotalCount();
public void getPageData(PageBean<Employee> pb);	
}
接下來實現這兩個介面,記住步驟:準備sql語句,獲得JdbcUtil的QueryRunner使用query()方法執行sql語句

在sql語句中的分頁語句是select * from 表 limt ?,?分別是查詢的起始行和查詢的行數

package cn.itcast.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import cn.itcast.dao.UserDao;
import cn.itcast.entity.Employee;
import cn.itcast.utils.JdbcUtils;
import cn.itcast.utils.PageBean;

public class UserDaoImpl implements UserDao{

	@Override
	public int getTotalCount() {
		String sql="select count(*) from Employee";
		
		try {
			QueryRunner qr = JdbcUtils.getQueryRuner();
			Long count=qr.query(sql, new ScalarHandler<Long>());
			return count.intValue();
		} catch (SQLException e) {
			
			throw new RuntimeException(e);
		}
		
		
	}

	@Override
	public void getPageData(PageBean<Employee> pb) {
		int totalCount=getTotalCount();
		pb.setTotalCount(totalCount);		
		if(pb.getCurrentPage()<1){
			pb.setCurrentPage(1);
		}else if(pb.getCurrentPage()>pb.getTotalPage()){
			pb.setCurrentPage(pb.getTotalPage());
		}
		
		try {
			int first=(pb.getCurrentPage()-1)*pb.getPageCount();
			int count=pb.getPageCount();
			String sql="select * from Employee limit ?,?";
			QueryRunner qr = JdbcUtils.getQueryRuner();
			List<Employee> list=qr.query(sql, new BeanListHandler<Employee>(Employee.class),first,count);
			pb.setPageData(list);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
	}

}
接下來是我們業務邏輯層介面的設計,我們在資料訪問層中的一個獲得總記錄方法在獲得查詢資料方法中填充了,我們只需要在業務邏輯層實現分頁查詢資料介面就可以

package cn.itcast.service;

import cn.itcast.entity.Employee;
import cn.itcast.utils.PageBean;

public interface IEmployeeService {
	public void getAll(PageBean<Employee> pb);
}
接下來實現這個

public class UserDaoService implements IEmployeeService{

	private UserDao userDao = new UserDaoImpl();
	public void getAll(PageBean<Employee> pb) {
		userDao.getPageData(pb);
		
	}

}
接下來我們寫控制層,我們先獲得檢視層傳來的當前頁值,將當前頁值轉換整形,傳給pageBean中的當前頁,呼叫service方法的分頁方法將pageBean類填充分頁資料,將物件傳回頁面

public class IndexServlet extends HttpServlet {
	// 建立Service例項
	private IEmployeeService employeeService = new EmployeeService();
	// 跳轉資源
	private String uri;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		try {
			//1. 獲取“當前頁”引數;  (第一次訪問當前頁為null) 
			String currPage = request.getParameter("currentPage");
			// 判斷
			if (currPage == null || "".equals(currPage.trim())){
				currPage = "1";  	// 第一次訪問,設定當前頁為1;
			}
			// 轉換
			int currentPage = Integer.parseInt(currPage);
			
			//2. 建立PageBean物件,設定當前頁引數; 傳入service方法引數
			PageBean<Employee> pageBean = new PageBean<Employee>();
			pageBean.setCurrentPage(currentPage);
			
			//3. 呼叫service  
			employeeService.getAll(pageBean);    // 【pageBean已經被dao填充了資料】
			
			//4. 儲存pageBean物件,到request域中
			request.setAttribute("pageBean", pageBean);
			
			//5. 跳轉 
			uri = "/WEB-INF/list.jsp";
		} catch (Exception e) {
			e.printStackTrace();  // 測試使用
			// 出現錯誤,跳轉到錯誤頁面;給使用者友好提示
			uri = "/error/error.jsp";
		}
		request.getRequestDispatcher(uri).forward(request, response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}
接下來我們來完成顯示的頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!-- 引入jstl核心標籤庫 -->
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>分頁查詢資料</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
  
  <body>
  	<table border="1" width="80%" align="center" cellpadding="5" cellspacing="0">
  		<tr>
  			<td>序號</td>
  			<td>員工編號</td>
  			<td>員工姓名</td>
  		</tr>
  		<!-- 迭代資料 -->
  		<c:choose>
  			<c:when test="${not empty requestScope.pageBean.pageData}">
  				<c:forEach var="emp" items="${requestScope.pageBean.pageData}" varStatus="vs">
  					<tr>
  						<td>${vs.count }</td>
  						<td>${emp.empId }</td>
  						<td>${emp.empName }</td>
  					</tr>
  				</c:forEach>
  			</c:when>
  			<c:otherwise>
  				<tr>
  					<td colspan="3">對不起,沒有你要找的資料</td>
  				</tr>
  			</c:otherwise>
  		</c:choose>
  		
  		<tr>
  			<td colspan="3" align="center">
  				當前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }頁       
  				
  				<a href="${pageContext.request.contextPath }/index?currentPage=1">首頁</a>
  				<a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage-1}">上一頁 </a>
  				<a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage+1}">下一頁 </a>
  				<a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.totalPage}">末頁</a>
  			</td>
  		</tr>
  		
  	</table>
  </body>
</html>









到這裡我們就完成分頁了