jsp web分页简单实现

web分页

 

为什么需要分页?

一、数据方面的原因

大量查询的数据耗时比较严重。

二、增强用户使用体验需求

用户更方便的查询和展示他所需要的数据。

 

常见分页方式:传统分页方式和下拉式分页方式。

采用传统的分页方式,可以明确的获取数据信息,如有多少条数据,分多少页显示。

采用下拉式分页方式,一般无法获取明确的数据数量相关的信息,但是在分页操作以后,仍然可以看到之前查询的数据。

 

常见的分页实现方式

1.      使用subList()实现分页。

List<E> subList(int fromIndex,int toIndex)

返回列表中指定的fromIndex(包含)和 toIndex (不包括)之间的部分视图。

2.      使用SQL语句实现分页

利用数据库自带的分页语法,使用分页语句,获取分页数据(例如mysql数据库使用limit关键字,oracle中使用rownum关键字等)

Mysql

-         select * from students limit0,10   从第0条开始查,一共查询10条记录。

3.      使用hibernate框架进行分页。

创建Query或者Criteria对象,查询时,设置firstResult(从第几条开始查)和maxResults(查询几条记录)属性。

String hql = “ from Student”;

Query q = session.createQuery(hql);

q.setFirstResult(0);

q.setMaxResults(10);

List l = q.list();

 

实现方式

优点

缺点

使用场景

subList

简单、易用

效率低

无法按需批量获取数据

SQL语句

简单、直接、效率高

数据库兼容性差

不要求数据库兼容

Hibernate框架

面向对象,兼容性强

复杂查询性能低

兼容不同数据库

 

1.      使用sublist实现分页。


创建model层

学生对象 Student类

  1. public class Student implements Serializable{
  2. /**
  3. *
  4. */
  5. private static final long serialVersionUID = - 2448260736229612919L; //序列化id
  6. private int id; //学生记录的id
  7. private String stuName; //姓名
  8. private int age; //年龄
  9. private int gender; //性别
  10. private String address; //地址
  11. public Student(){
  12. super();
  13. }
  14. public Student(int id, String stuName, int age, int gender, String address) {
  15. super();
  16. this.id = id;
  17. this.stuName = stuName;
  18. this.age = age;
  19. this.gender = gender;
  20. this.address = address;
  21. }
  22. /*
  23. * 构造函数,将查询到的Map类型的数据构造成学生对象
  24. */
  25. public Student(Map<String,Object> map){
  26. this.id = ( int)map.get( "id");
  27. this.stuName = (String)map.get( "stu_name");
  28. this.age = ( int)map.get( "age");
  29. this.gender = ( int)map.get( "gender");
  30. this.address = (String)map.get( "address");
  31. }
  32. }
分页对象 Pager类

  1. public class Pager<T> implements Serializable{
  2. /**
  3. * 序列化id
  4. */
  5. private static final long serialVersionUID = 7569566861340703188L;
  6. private int pageSize; //每页显示多少条记录
  7. private int currentPage; //当前第几页数据
  8. private int totalRecord; //一共多少条记录
  9. private List<T> dataList; //要显示的数据
  10. private int totalPage; //总页数
  11. public Pager() {
  12. super();
  13. }
  14. public Pager(int pageSize, int currentPage, int totalRecord,
  15. int totalPage,List<T> dataList) {
  16. super();
  17. this.pageSize = pageSize;
  18. this.currentPage = currentPage;
  19. this.totalRecord = totalRecord;
  20. this.totalPage = totalPage;
  21. this.dataList = dataList;
  22. }
  23. public Pager(int pageNum,int pageSize,List<T> sourceList){
  24. if(sourceList.size() == 0 ||sourceList == null){
  25. return;
  26. }
  27. //总记录条数
  28. this.totalRecord = sourceList.size();
  29. //每页显示多少条记录
  30. this.pageSize = pageSize;
  31. //获取总页数
  32. this.totalPage = this.totalRecord / this.pageSize;
  33. if( this.totalRecord % this.pageSize != 0){
  34. this.totalPage = this.totalPage + 1;
  35. }
  36. //当前第几页数据
  37. if( this.totalPage < pageNum){
  38. this.currentPage = this.totalPage;
  39. } else{
  40. this.currentPage = pageNum;
  41. }
  42. //起始索引
  43. int fromIndex = this.pageSize*( this.currentPage- 1);
  44. //结束索引
  45. int toIndex;
  46. if( this.pageSize * this.currentPage > this.totalRecord){
  47. toIndex = this.totalRecord;
  48. } else{
  49. toIndex = this.pageSize * this.currentPage;
  50. }
  51. this.dataList = sourceList.subList(fromIndex, toIndex);
  52. }
  53. }
数据库工具类 JdbcUtil.java

  1. public class JdbcUtil {
  2. //表示定义数据库的用户名
  3. private static String USERNAME;
  4. //定义数据库的密码
  5. private static String PASSWORD;
  6. //定义数据库的驱动信息
  7. private static String DRIVER;
  8. //定义访问数据库的地址
  9. private static String URL;
  10. //定义数据库的连接
  11. private Connection connection;
  12. //定义sql语句的执行对象
  13. private PreparedStatement pstmt;
  14. //定义查询返回的结果集合
  15. private ResultSet resultSet;
  16. static{
  17. loadConfig();
  18. }
  19. /**
  20. * 加载数据库配置文件,并给相关的属性赋值,配置信息写在配置文件中,方便管理
  21. */
  22. public static void loadConfig(){
  23. //路径 WEB-INF\classes\jdbc.properties
  24. InputStream inStream = JdbcUtil.class.getResourceAsStream( "/jdbc.properties");
  25. Properties prop = new Properties();
  26. try{
  27. prop.load(inStream);
  28. USERNAME = prop.getProperty( "jdbc.username");
  29. PASSWORD = prop.getProperty( "jdbc.password");
  30. DRIVER= prop.getProperty( "jdbc.driver");
  31. URL = prop.getProperty( "jdbc.url");
  32. } catch(Exception e){
  33. throw new RuntimeException( "读取用户配置文件出错",e);
  34. }
  35. }
  36. /**
  37. * 获取数据库连接
  38. */
  39. public Connection getConnection(){
  40. try {
  41. Class.forName(DRIVER); //注册驱动
  42. //获取连接对象
  43. connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
  44. } catch (ClassNotFoundException e) {
  45. e.printStackTrace();
  46. } catch (SQLException e) {
  47. e.printStackTrace();
  48. }
  49. return connection;
  50. }
  51. /**
  52. * 执行更新操作
  53. * sql sql语句
  54. * params 执行参数
  55. * return 执行结果
  56. */
  57. public boolean updateByPreparedStatement(String sql,List<?> params)throws SQLException{
  58. boolean flag = false;
  59. int result = - 1; //表示用户执行添加删除和修改的时候所影响数据库的行数
  60. pstmt = connection.prepareStatement(sql);
  61. int index = 1;
  62. //填充sql语句中的占位符
  63. if(params != null && !params.isEmpty()){
  64. for( int i= 0;i < params.size();i++){
  65. pstmt.setObject(index ++, params.get(i));
  66. }
  67. }
  68. result = pstmt.executeUpdate();
  69. flag = result > 0 ? true : false;
  70. return flag;
  71. }
  72. /**
  73. * 执行查询操作
  74. * sql sql语句
  75. * params 执行参数
  76. */
  77. public List<Map<String, Object>> findResult(String sql,List<?> params) throws SQLException{
  78. List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
  79. int index = 1;
  80. pstmt = connection.prepareStatement(sql);
  81. /*
  82. * 填充查询语句的参数
  83. */
  84. if(params != null && !params.isEmpty()){
  85. for( int i = 0;i<params.size();i++){
  86. pstmt.setObject(index ++, params.get(i));
  87. }
  88. }
  89. resultSet = pstmt.executeQuery();
  90. /*
  91. * 通过ResultSetMetaData获取一个ResultSet的列的类型和关于列的属性信息,如列名、列数等
  92. */
  93. ResultSetMetaData metaData = resultSet.getMetaData();
  94. //获取列的数量
  95. int cols_len = metaData.getColumnCount();
  96. /*
  97. * 遍历resultSet
  98. */
  99. while(resultSet.next()){
  100. Map<String,Object> map = new HashMap<String, Object>();
  101. for( int i= 0;i<cols_len;i++){
  102. //获取列名
  103. String cols_name = metaData.getColumnName(i+ 1);
  104. //根据列名获取列值
  105. Object cols_value = resultSet.getObject(cols_name);
  106. if(cols_value == null){
  107. cols_value = "";
  108. }
  109. map.put(cols_name, cols_value);
  110. }
  111. list.add(map);
  112. }
  113. return list;
  114. }
  115. /**
  116. * 释放资源
  117. *
  118. */
  119. public void releaseConn(){
  120. if(resultSet != null){
  121. try {
  122. resultSet.close();
  123. } catch (SQLException e) {
  124. e.printStackTrace();
  125. }
  126. }
  127. if(pstmt != null){
  128. try {
  129. pstmt.close();
  130. } catch (SQLException e) {
  131. e.printStackTrace();
  132. }
  133. }
  134. if(connection != null){
  135. try {
  136. connection.close();
  137. } catch (SQLException e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. }
  142. }
数据库配置文件

jdbc.username=root
jdbc.password=limeng
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://127.0.0.1\:3306/pager

创建Dao层,数据操作对象

接口 StudentDao.java

  1. public interface StudentDao {
  2. /**
  3. * 根据查询条件,查询学生分页信息
  4. * @param searchModel 封装查询条件
  5. * @param pageNum 查询第几条数据
  6. * @param pageSize 显示多少数据
  7. * @return
  8. */
  9. public Pager<Student> findStudent(Student searchModel,int pageNum,int pageSize);
  10. }
Dao层接口实现类 SublistStudentDaoImpl.java

  1. public class SublistStudentDaoImpl implements StudentDao{
  2. @Override
  3. public Pager<Student> findStudent(Student searchModel, int pageNum,
  4. int pageSize) {
  5. /*
  6. * 根据条件获取所有数据
  7. */
  8. List<Student> allStudentList = getAllStudent(searchModel);
  9. /*
  10. * 根据参数创建分页对象
  11. */
  12. Pager<Student> pager = new Pager<Student>(pageNum,pageSize,allStudentList);
  13. return pager;
  14. }
  15. /*
  16. * 获取所有数据
  17. */
  18. private List<Student> getAllStudent(Student searchModel){
  19. List<Student> result = new ArrayList<Student>();
  20. List<Object> paramList = new ArrayList<Object>();
  21. String stuName = searchModel.getStuName();
  22. int gender = searchModel.getGender();
  23. StringBuilder sql = new StringBuilder( "select * from t_student where 1=1");
  24. if(stuName != null && !stuName.equals( "")){
  25. sql.append( " and stu_name like ?");
  26. paramList.add( "%"+stuName+ "%");
  27. }
  28. if(gender == Constant.GENDER_FEMALE || gender== Constant.GENDER_MALE){
  29. sql.append( " and gender = ?");
  30. paramList.add(gender);
  31. }
  32. JdbcUtil jdbcUtil = null;
  33. try {
  34. jdbcUtil = new JdbcUtil();
  35. jdbcUtil.getConnection();
  36. List<Map<String, Object>> mapList = jdbcUtil.findResult(sql.toString(), paramList);
  37. if(mapList != null){
  38. for(Map<String, Object> map : mapList){
  39. Student s = new Student(map);
  40. result.add(s);
  41. }
  42. }
  43. } catch (SQLException e) {
  44. throw new RuntimeException( "查询所有数据异常!",e);
  45. } finally{
  46. if(jdbcUtil != null){
  47. jdbcUtil.releaseConn();
  48. }
  49. }
  50. return result;
  51. }
  52. }
创建Service层,调用Dao层

  1. public class SublistStudentServiceImpl implements StudentService{
  2. private StudentDao studentDao;
  3. public SublistStudentServiceImpl(){
  4. //创建service实现类时,初始化dao对象
  5. studentDao = new SublistStudentDaoImpl();
  6. }
  7. @Override
  8. public Pager<Student> findStudent(Student searchModel, int pageNum,
  9. int pageSize) {
  10. Pager<Student> result = studentDao.findStudent(searchModel, pageNum, pageSize);
  11. return result;
  12. }
  13. public StudentDao getStudentDao() {
  14. return studentDao;
  15. }
  16. public void setStudentDao(StudentDao studentDao) {
  17. this.studentDao = studentDao;
  18. }
  19. }
创建Servlet,接收参数,调用Service层

  1. public class SublistServlet extends HttpServlet {
  2. //创建service对象
  3. private StudentService studentService = new SublistStudentServiceImpl();
  4. public SublistServlet() {
  5. super();
  6. }
  7. public void destroy() {
  8. super.destroy(); // Just puts "destroy" string in log
  9. // Put your code here
  10. }
  11. public void doGet(HttpServletRequest request, HttpServletResponse response)
  12. throws ServletException, IOException {
  13. doPost(request, response);
  14. }
  15. public void doPost(HttpServletRequest request, HttpServletResponse response)
  16. throws ServletException, IOException {
  17. /*
  18. * 设置编码格式,防止解析中文参数乱码
  19. */
  20. request.setCharacterEncoding( "utf-8");
  21. /* 接收request参数
  22. * 学生姓名
  23. */
  24. String stuName = request.getParameter( "stuName");
  25. /*
  26. * 性别,默认是0,表示全部,不论男女
  27. */
  28. int gender = Constant.DEFAULT_GENDER;
  29. String genderStr = request.getParameter( "gender");
  30. if(genderStr != null && ! "".equals(genderStr.trim())){
  31. gender = Integer.parseInt(genderStr); // 获取学生性别
  32. }
  33. /*
  34. * 当前请求第几页
  35. */
  36. int pageNum = Constant.DEFAULT_PAGENUM;
  37. String pageNumStr = request.getParameter( "pageNum");
  38. //参数校验,是否是数字
  39. if(pageNumStr != null && !StringUtil.isNum(pageNumStr)){
  40. request.setAttribute( "errorMsg", "参数输入错误");
  41. request.getRequestDispatcher( "sublistStudent.jsp").forward(request,
  42. response);
  43. return;
  44. }
  45. if(pageNumStr != null && ! "".equals(pageNumStr.trim())){
  46. pageNum = Integer.parseInt(pageNumStr); //获取当前请求第几页
  47. }
  48. /*
  49. * 每页显示多少条数据
  50. */
  51. int pageSize = Constant.DEFAULT_PAGE_SIZE;
  52. String pageSizeStr = request.getParameter( "pageSize");
  53. if(pageSizeStr != null && ! "".equals(pageSizeStr.trim())){
  54. pageSize = Integer.parseInt(pageSizeStr); // 每页显示多少条记录
  55. }
  56. // 组装查询条件
  57. Student searchModel = new Student();
  58. searchModel.setStuName(stuName);
  59. searchModel.setGender(gender);
  60. // 调用service查询结果
  61. Pager<Student> result = studentService.findStudent(searchModel,
  62. pageNum, pageSize);
  63. // 返回结果到页面
  64. request.setAttribute( "result", result);
  65. request.getRequestDispatcher( "sublistStudent.jsp").forward(request,
  66. response);
  67. }
  68. }
Jsp页面

  1. <%@ page language= "java" contentType= "text/html; charset=UTF-8"
  2. pageEncoding= "UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <% @taglib prefix= "c" uri= "http://java.sun.com/jsp/jstl/core" %>
  5. <% @taglib prefix= "fn" uri= "http://java.sun.com/jsp/jstl/functions" %>
  6. <html>
  7. <head>
  8. <meta http-equiv= "Content-Type" content= "text/html; charset=UTF-8">
  9. <title>学生信息</title>
  10. </head>
  11. <%
  12. // 获取请求的上下文
  13. String context = request.getContextPath();
  14. %>
  15. <script type= "text/javascript">
  16. // 当前第几页数据
  17. var currentPage = ${result.currentPage};
  18. // 总页数
  19. var totalPage = ${result.totalPage};
  20. function submitForm(actionUrl){
  21. var formElement = document.getElementById( "stuForm");
  22. formElement.action = actionUrl;
  23. formElement.submit();
  24. }
  25. // 第一页
  26. function firstPage(){
  27. if(currentPage == 1){
  28. alert( "已经是第一页数据");
  29. return false;
  30. } else{
  31. submitForm( "<%=context %>/sublist/SublistServlet?pageNum=1");
  32. return true;
  33. }
  34. }
  35. // 下一页
  36. function nextPage(){
  37. if(currentPage == totalPage){
  38. alert( "已经是最后一页数据");
  39. return false;
  40. } else{
  41. submitForm( "<%=context %>/sublist/SublistServlet?pageNum=" + (currentPage+ 1));
  42. return true;
  43. }
  44. }
  45. // 上一页
  46. function previousPage(){
  47. if(currentPage == 1){
  48. alert( "已经是第一页数据");
  49. return false;
  50. } else{
  51. submitForm( "<%=context %>/sublist/SublistServlet?pageNum=" + (currentPage- 1));
  52. return true;
  53. }
  54. }
  55. // 尾页
  56. function lastPage(){
  57. if(currentPage == totalPage){
  58. alert( "已经是最后一页数据");
  59. return false;
  60. } else{
  61. submitForm( "<%=context %>/sublist/SublistServlet?pageNum=${result.totalPage}");
  62. return true;
  63. }
  64. }
  65. /*
  66. * 在初次加载时默认选择全部
  67. */
  68. function initPage(){
  69. var genderRequest = "${gender}" ;
  70. var genderVal = 0;
  71. var genderElement = document.getElementById( "gender");
  72. if(genderRequest != ""){
  73. genderVal = parseInt(genderRequest);
  74. }
  75. var options = genderElement.options;
  76. var i = 0;
  77. for(i = 0; i < options.length; i++){
  78. if(options[i].value == genderVal){
  79. options[i].selected= true;
  80. break;
  81. }
  82. }
  83. }
  84. </script>
  85. <body onload= "initPage();">
  86. <div style= "margin-left: 100px; margin-top: 100px;">
  87. <div>
  88. <font color= "red">${errorMsg }</font>
  89. </div>
  90. <div>
  91. <form action= "<%=context %>/sublist/SublistServlet" id= "stuForm" method= "post">
  92. 姓名
  93. <input type= "text" name= "stuName" id= "stu_name" style= "width:120px" value= "${stuName }">
  94.  
  95. 性别
  96. <select name= "gender" id= "gender" style= "width:80px">
  97. <option value= "0">全部</option>
  98. <option value= "1">男</option>
  99. <option value= "2">女</option>
  100. </select>
  101.   
  102. <input type= "submit" value= "查询">
  103. </form>
  104. </div>
  105. <br>
  106. 学生信息列表:<br>
  107. <br>
  108. <!-- 后台返回结果为空 -->
  109. <c: if test= "${fn:length(result.dataList) eq 0 }">
  110. <span>查询的结果不存在</span>
  111. </c: if>
  112. <!-- 后台返回结果不为空 -->
  113. <c: if test= "${fn:length(result.dataList) gt 0 }">
  114. <table border= "1px" cellspacing= "0px"
  115. style= "border-collapse: collapse">
  116. <thead>
  117. <tr height= "30">
  118. <th width= "130">姓名</th>
  119. <th width= "130">性别</th>
  120. <th width= "130">年龄</th>
  121. <th width= "190">家庭地址</th>
  122. </tr>
  123. </thead>
  124. <c:forEach items= "${result.dataList }" var= "student">
  125. <tr>
  126. <td><c:out value= "${student.stuName}"></c:out></td>
  127. <td>
  128. <c: if test= "${ student.gender eq 1}">男</c: if>
  129. <c: if test= "${ student.gender eq 2}">女</c: if>
  130. </td>
  131. <td><c:out value= "${student.age }"></c:out></td>
  132. <td><c:out value= "${student.address }"></c:out></td>
  133. </tr>
  134. </c:forEach>
  135. </table>
  136. <br> 共${result.totalRecord }条记录共${result.totalPage }页  当前第${result.currentPage }页  
  137. <a href= "#" onclick= "firstPage();">首页</a>  
  138. <a href= "#" onclick= "nextPage();">下一页</a>  
  139. <a href= "#" onclick= "previousPage();">上一页</a>  
  140. <a href= "#" onblur= "lastPage();">尾页</a>
  141. </c: if>
  142. </div>
  143. </body>
  144. </html>
原文链接:https://blog.csdn.net/u010583599/article/details/54947289

猜你喜欢

转载自blog.csdn.net/qq_30764991/article/details/80879223