Java分頁技術的實現(一)
阿新 • • 發佈:2019-01-03
(一)建立一個web專案
(二)編寫Java類
1.建立一個com.imooc.page包
package com.imooc.page;
public class Constant {
/**
* 男性
*/
public static final int GENDER_MALE = 1;
/**
* 女性
*/
public static final int GENDER_FEMALE = 2;
/**
* 預設每頁顯示多少條記錄
*/
public static final int DEFAULT_PAGE_SIZE = 5;
/**
* 預設顯示第幾頁記錄
*/
public static final int DEFAULT_PAGE_NUM = 1;
/**
* 預設學生性別
*/
public static final int DEFAULT_GENDER = 0;
}
///////////////////////////////////////////////////////////
package com.imooc.page;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request,response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
2.建立一個com.imooc.page,model
package com.imooc.page.model;
import java.io.Serializable;
import java.util.List;
public class Pager<T> implements Serializable {
private static final long serialVersionUID = -8741766802354222579L;
private int pageSize; // 每頁顯示多少條記錄
private int currentPage; //當前第幾頁資料
private int totalRecord; // 一共多少條記錄
private int totalPage; // 一共多少頁記錄
private List<T> dataList; //要顯示的資料
public Pager(int pageNum, int pageSize, List<T> sourceList){
if(sourceList == null || sourceList.isEmpty()){
return;
}
// 總記錄條數
this.totalRecord = sourceList.size();
// 每頁顯示多少條記錄
this.pageSize = pageSize;
//獲取總頁數
this.totalPage = this.totalRecord / this.pageSize;
if(this.totalRecord % this.pageSize !=0){
this.totalPage = this.totalPage + 1;
}
// 當前第幾頁資料
this.currentPage = this.totalPage < pageNum ? this.totalPage : pageNum;
// 起始索引
int fromIndex = this.pageSize * (this.currentPage -1);
// 結束索引
int toIndex = this.pageSize * this.currentPage > this.totalRecord ? this.totalRecord : this.pageSize * this.currentPage;
this.dataList = sourceList.subList(fromIndex, toIndex);
}
public Pager(){
}
public Pager(int pageSize, int currentPage, int totalRecord, int totalPage,
List<T> dataList) {
super();
this.pageSize = pageSize;
this.currentPage = currentPage;
this.totalRecord = totalRecord;
this.totalPage = totalPage;
this.dataList = dataList;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getDataList() {
return dataList;
}
public void setDataList(List<T> dataList) {
this.dataList = dataList;
}
}
//////////////////////////////////////////////////////////
package com.imooc.page.model;
import java.io.Serializable;
import java.util.Map;
public class Student implements Serializable {
private static final long serialVersionUID = -7476381137287496245L;
private int id; //學生記錄id
private String stuName;//學生姓名
private int age; //學生年齡
private int gender; //學生性別
private String address;//學生住址
public Student() {
super();
}
public Student(int id, String stuName, int age, int gender, String address) {
super();
this.id = id;
this.stuName = stuName;
this.age = age;
this.gender = gender;
this.address = address;
}
public Student(Map<String, Object> map){
this.id = (int)map.get("id");
this.stuName = (String)map.get("stu_name");
this.age = (int)map.get("age");
this.gender = (int)map.get("gender");
this.address = (String)map.get("address");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Student [id=" + id + ", stuName=" + stuName + ", age=" + age
+ ", gender=" + gender + ", address=" + address + "]";
}
}
3.建立一個com.imooc.page.dao包
package com.imooc.page.dao;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public interface StudentDao {
/**
* 根據查詢條件,查詢學生分頁資訊
*
* @param searchModel
* 封裝查詢條件
* @param pageNum
* 查詢第幾頁資料
* @param pageSize
* 每頁顯示多少條記錄
* @return 查詢結果
*/
public Pager<Student> findStudent(Student searchModel, int pageNum,
int pageSize);
}
//////////////////////////////////////////////////////////////////
package com.imooc.page.dao;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.imooc.page.Constant;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
import com.imooc.page.util.JdbcUtil;
public class SublistStudentDaoImpl implements StudentDao {
@Override
public Pager<Student> findStudent(Student searchModel, int pageNum,
int pageSize) {
List<Student> allStudenList = getAllStudent(searchModel);
Pager<Student> pager = new Pager<Student>(pageNum, pageSize,
allStudenList);
return pager;
}
/**
* 模仿獲取所有資料
*
* @param searchModel
* 查詢引數
* @return 查詢結果
*/
private static List<Student> getAllStudent(Student searchModel) {
List<Student> result = new ArrayList<Student>();
List<Object> paramList = new ArrayList<Object>();
String stuName = searchModel.getStuName();
int gender = searchModel.getGender();
StringBuilder sql = new StringBuilder(
"select * from t_student where 1=1");
if (stuName != null && !stuName.equals("")) {
sql.append(" and stu_name like ?");
paramList.add("%" + stuName + "%");
}
if (gender == Constant.GENDER_FEMALE || gender == Constant.GENDER_MALE) {
sql.append(" and gender = ?");
paramList.add(gender);
}
JdbcUtil jdbcUtil = null;
try {
jdbcUtil = new JdbcUtil();
jdbcUtil.getConnection(); // 獲取資料庫連結
List<Map<String, Object>> mapList = jdbcUtil.findResult(
sql.toString(), paramList);
if (mapList != null) {
for (Map<String, Object> map : mapList) {
Student s = new Student(map);
result.add(s);
}
}
} catch (SQLException e) {
throw new RuntimeException("查詢所有資料異常!", e);
} finally {
if (jdbcUtil != null) {
jdbcUtil.releaseConn(); // 一定要釋放資源
}
}
return result;
}
public static void main(String[] args) {
List<Student> lst = getAllStudent(new Student());
for (Student s : lst) {
System.out.println(s);
}
}
}
4.建立一個com.imooc.page.service包
package com.imooc.page.service;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public interface StudentService {
/**
* 根據查詢條件,查詢學生分頁資訊
*
* @param searchModel
* 封裝查詢條件
* @param pageNum
* 查詢第幾頁資料
* @param pageSize
* 每頁顯示多少條記錄
* @return 查詢結果
*/
public Pager<Student> findStudent(Student searchModel, int pageNum,
int pageSize);
}
////////////////////////////////////////////////////////////////
package com.imooc.page.service;
import com.imooc.page.dao.StudentDao;
import com.imooc.page.dao.SublistStudentDaoImpl;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
public class SublistStudentServiceImpl implements StudentService {
private StudentDao studentDao;
public SublistStudentServiceImpl() {
// 建立servivce實現類時,初始化dao物件。
studentDao = new SublistStudentDaoImpl();
}
@Override
public Pager<Student> findStudent(Student searchModel, int pageNum,
int pageSize) {
Pager<Student> result = studentDao.findStudent(searchModel, pageNum,
pageSize);
return result;
}
public StudentDao getStudentDao() {
return studentDao;
}
public void setStudentDao(StudentDao studentDao) {
this.studentDao = studentDao;
}
}
5.建立一個com.imooc.page.servlet包
package com.imooc.page.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.imooc.page.Constant;
import com.imooc.page.model.Pager;
import com.imooc.page.model.Student;
import com.imooc.page.service.StudentService;
import com.imooc.page.service.SublistStudentServiceImpl;
import com.imooc.page.util.StringUtil;
public class SublistServlet extends HttpServlet {
private static final long serialVersionUID = -3658128508633145268L;
private StudentService studentService = new SublistStudentServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 接收request裡的引數
String stuName = request.getParameter("stuName"); //學生姓名
// 獲取學生性別
int gender = Constant.DEFAULT_GENDER;
String genderStr = request.getParameter("gender");
if(genderStr!=null && !"".equals(genderStr.trim())){
gender = Integer.parseInt(genderStr);
}
// 校驗pageNum引數輸入合法性
String pageNumStr = request.getParameter("pageNum");
if(pageNumStr !=null && !StringUtil.isNum(pageNumStr)){
request.setAttribute("errorMsg", "引數傳輸錯誤");
request.getRequestDispatcher("sublistStudent.jsp").forward(request, response);
return;
}
int pageNum = Constant.DEFAULT_PAGE_NUM; //顯示第幾頁資料
if(pageNumStr!=null && !"".equals(pageNumStr.trim())){
pageNum = Integer.parseInt(pageNumStr);
}
int pageSize = Constant.DEFAULT_PAGE_SIZE; // 每頁顯示多少條記錄
String pageSizeStr = request.getParameter("pageSize");
if(pageSizeStr!=null && !"".equals(pageSizeStr.trim())){
pageSize = Integer.parseInt(pageSizeStr);
}
// 組裝查詢條件
Student searchModel = new Student();
searchModel.setStuName(stuName);
searchModel.setGender(gender);
//呼叫service 獲取查詢結果
Pager<Student> result = studentService.findStudent(searchModel,
pageNum, pageSize);
// 返回結果到頁面
request.setAttribute("result", result);
request.setAttribute("stuName", stuName);
request.setAttribute("gender", gender);
request.getRequestDispatcher("sublistStudent.jsp").forward(request, response);
}
}
6.建立一個com.imooc.page.Util包
package com.imooc.page.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class JdbcUtil {
// 表示定義資料庫的使用者名稱
private static String USERNAME ;
// 定義資料庫的密碼
private static String PASSWORD;
// 定義資料庫的驅動資訊
private static String DRIVER;
// 定義訪問資料庫的地址
private static String URL;
// 定義資料庫的連結
private Connection connection;
// 定義sql語句的執行物件
private PreparedStatement pstmt;
// 定義查詢返回的結果集合
private ResultSet resultSet;
static{
//載入資料庫配置資訊,並給相關的屬性賦值
loadConfig();
}
/**
* 載入資料庫配置資訊,並給相關的屬性賦值
*/
public static void loadConfig() {
try {
InputStream inStream = JdbcUtil.class
.getResourceAsStream("/jdbc.properties");
Properties prop = new Properties();
prop.load(inStream);
USERNAME = prop.getProperty("jdbc.username");
PASSWORD = prop.getProperty("jdbc.password");
DRIVER= prop.getProperty("jdbc.driver");
URL = prop.getProperty("jdbc.url");
} catch (Exception e) {
throw new RuntimeException("讀取資料庫配置檔案異常!", e);
}
}
public JdbcUtil() {
}
/**
* 獲取資料庫連線
*
* @return 資料庫連線
*/
public Connection getConnection() {
try {
Class.forName(DRIVER); // 註冊驅動
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD); // 獲取連線
} catch (Exception e) {
throw new RuntimeException("get connection error!", e);
}
return connection;
}
/**
* 執行更新操作
*
* @param sql
* sql語句
* @param params
* 執行引數
* @return 執行結果
* @throws SQLException
*/
public boolean updateByPreparedStatement(String sql, List<?> params)
throws SQLException {
boolean flag = false;
int result = -1;// 表示當用戶執行新增刪除和修改的時候所影響資料庫的行數
pstmt = connection.prepareStatement(sql);
int index = 1;
// 填充sql語句中的佔位符
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
result = pstmt.executeUpdate();
flag = result > 0 ? true : false;
return flag;
}
/**
* 執行查詢操作
*
* @param sql
* sql語句
* @param params
* 執行引數
* @return
* @throws SQLException
*/
public List<Map<String, Object>> findResult(String sql, List<?> params)
throws SQLException {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
int index = 1;
pstmt = connection.prepareStatement(sql);
if (params != null && !params.isEmpty()) {
for (int i = 0; i < params.size(); i++) {
pstmt.setObject(index++, params.get(i));
}
}
resultSet = pstmt.executeQuery();
ResultSetMetaData metaData = resultSet.getMetaData();
int cols_len = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> map = new HashMap<String, Object>();
for (int i = 0; i < cols_len; i++) {
String cols_name = metaData.getColumnName(i + 1);
Object cols_value = resultSet.getObject(cols_name);
if (cols_value == null) {
cols_value = "";
}
map.put(cols_name, cols_value);
}
list.add(map);
}
return list;
}
/**
* 釋放資源
*/
public void releaseConn() {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
JdbcUtil jdbcUtil = new JdbcUtil();
jdbcUtil.getConnection();
try {
List<Map<String, Object>> result = jdbcUtil.findResult(
"select * from t_student", null);
for (Map<String, Object> m : result) {
System.out.println(m);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
jdbcUtil.releaseConn();
}
}
}
//////////////////////////////////////////////////////////////
package com.imooc.page.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtil {
/**
* 校驗字串是否是大於0的數字
* @param string
* @return
*/
public static boolean isNum(String string){
Pattern pattern = Pattern.compile("[1-9]{1}\\d*");
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
}
(三)在page專案資料夾下建立一個config資料夾,在config資料夾下建立jdbc.properties檔案。
jdbc.username=root
jdbc.password=root
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/imooc
(四)在WebContext資料夾下建立sublist資料夾,在sublist資料夾下建立jsp頁面。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>學生資訊</title>
</head>
<%
// 獲取請求的上下文
String context = request.getContextPath();
%>
<script type="text/javascript">
// 當前第幾頁資料
var currentPage = ${result.currentPage};
// 總頁數
var totalPage = ${result.totalPage};
function submitForm(actionUrl){
var formElement = document.getElementById("stuForm");
formElement.action = actionUrl;
formElement.submit();
}
// 第一頁
function firstPage(){
if(currentPage == 1){
alert("已經是第一頁資料");
return false;
}else{
submitForm("<%=context %>/sublist/SublistServlet?pageNum=1");
return true;
}
}
// 下一頁
function nextPage(){
if(currentPage == totalPage){
alert("已經是最後一頁資料");
return false;
}else{
submitForm("<%=context %>/sublist/SublistServlet?pageNum=" + (currentPage+1));
return true;
}
}
// 上一頁
function previousPage(){
if(currentPage == 1){
alert("已經是第一頁資料");
return false;
}else{
submitForm("<%=context %>/sublist/SublistServlet?pageNum=" + (currentPage-1));
return true;
}
}
// 尾頁
function lastPage(){
if(currentPage == totalPage){
alert("已經是最後一頁資料");
return false;
}else{
submitForm("<%=context %>/sublist/SublistServlet?pageNum=${result.totalPage}");
return true;
}
}
function initPage(){
var genderRequest = "${gender}" ;
var genderVal = 0;
var genderElement = document.getElementById("gender");
if(genderRequest != ""){
genderVal = parseInt(genderRequest);
}
var options = genderElement.options;
var i = 0;
for(i = 0; i < options.length; i++){
if(options[i].value == genderVal){
options[i].selected=true;
break;
}
}
}
</script>
<body onload="initPage();">
<div style="margin-left: 100px; margin-top: 100px;">
<div>
<font color="red">${errorMsg }</font>
</div>
<div>
<form action="<%=context %>/sublist/SublistServlet" id="stuForm" method="post">
姓名
<input type="text" name="stuName" id="stu_name" style="width:120px" value="${stuName }">
性別
<select name="gender" id="gender" style="width:80px">
<option value="0">全部</option>
<option value="1">男</option>
<option value="2">女</option>
</select>
<input type="submit" value="查詢">
</form>
</div>
<br>
學生資訊列表:<br>
<br>
<!-- 後臺返回結果為空 -->
<c:if test="${fn:length(result.dataList) eq 0 }">
<span>查詢的結果不存在</span>
</c:if>
<!-- 後臺返回結果不為空 -->
<c:if test="${fn:length(result.dataList) gt 0 }">
<table border="1px" cellspacing="0px"
style="border-collapse: collapse">
<thead>
<tr height="30">
<th width="130">姓名</th>
<th width="130">性別</th>
<th width="130">年齡</th>
<th width="190">家庭地址</th>
</tr>
</thead>
<c:forEach items="${result.dataList }" var="student">
<tr>
<td><c:out value="${student.stuName }"></c:out></td>
<td>
<c:if test="${ student.gender eq 1}">男</c:if>
<c:if test="${ student.gender eq 2}">女</c:if>
</td>
<td><c:out value="${student.age }"></c:out></td>
<td><c:out value="${student.address }"></c:out></td>
</tr>
</c:forEach>
</table>
<br> 共${result.totalRecord }條記錄共${result.totalPage }頁 當前第${result.currentPage }頁
<a href="#" onclick="firstPage();">首頁</a>
<a href="#" onclick="nextPage();">下一頁</a>
<a href="#" onclick="previousPage();">上一頁</a>
<a href="#" onblur="lastPage();">尾頁</a>
</c:if>
</div>
</body>
</html>
(五)在WEB-INF資料夾下建立一個lib資料夾匯入相關jar包。
(六)在WEB-INF資料夾下建立一個web.xml配置檔案
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>pager</display-name>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.imooc.page.EncodingFilter</filter-class>
</filter>
<