你的位置:首页 > Java教程

[Java教程]java web 简单的分页显示


题外话:该分页显示是用 “表示层-控制层-DAO层-数据库”的设计思想实现的,有什么需要改进的地方大家提出来,共同学习进步。

思路:首先得在 DAO 对象中提供分页查询的方法,在控制层调用该方法查到指定页的数据,在表示层通过 EL 表达式和 JSTL 将该页数据显示出来。

重点:两个方法:(1)计算总的页数。 (2)查询指定页数据。

 

1.DAO层-数据库

JDBCUtils 类用于打开和关闭数据库,核心代码如下:

 1 import java.sql.Connection; 2 import java.sql.DriverManager; 3 import java.sql.PreparedStatement; 4 import java.sql.ResultSet; 5 import java.sql.SQLException; 6  7 public class JDBCUtils { 8   private Connection conn=null; 9   private PreparedStatement pstmt=null; 10   11   12   /**13    * connect 连接数据库14    * @return15   */16   public Connection connect(){17     String user="root";18     String password="1234";19     String driverClass = "com.mysql.jdbc.Driver";20     String jdbcUrl = "jdbc:mysql://localhost:3306/book";21     22     try {23       Class.forName(driverClass);24       conn = DriverManager.getConnection(jdbcUrl, user, password);25     } catch (Exception e) {26       // TODO Auto-generated catch block27       e.printStackTrace();28     }29     return conn;30     31   }32   33   /**34    * close 关闭数据库35    * @param conn36    * @param pstmt37    * @param resu38   */39   public void close(Connection conn,PreparedStatement pstmt,ResultSet result){40     if(conn != null){41       try {42         conn.close();43       } catch (SQLException e) {44         // TODO Auto-generated catch block45       }46     }47     if(pstmt != null){48       try {49         pstmt.close();50       } catch (SQLException e) {51         // TODO Auto-generated catch block52         e.printStackTrace();53       }54     }55     if(result != null){56       try {57         result.close();58       } catch (SQLException e) {59         // TODO Auto-generated catch block60         e.printStackTrace();61       }62     }63   }64 65 }

UserDao 类中的方法 getPage() 和方法 listUser() 分别用来计算总页数和查询指定页的数据,核心代码如下:

 1 import java.sql.Connection; 2 import java.sql.PreparedStatement; 3 import java.sql.ResultSet; 4 import java.sql.SQLException; 5 import java.util.ArrayList; 6 import java.util.List; 7  8 import com.db.JDBCUtils; 9 10 public class UserDao {11   /**12    * 计算总的页数13    * @return14   */15   public int getPage(){16     int recordCount=0,t1=0,t2=0;17     PreparedStatement pstmt=null;18     ResultSet result=null;19     JDBCUtils jdbc=new JDBCUtils();20     Connection conn=jdbc.connect();21     String sql="select count(*) from books";22     try {23       pstmt=conn.prepareStatement(sql);24       result=pstmt.executeQuery();25       result.next();26       recordCount=result.getInt(1);27       t1=recordCount%5;28       t2=recordCount/5;29     } catch (Exception e) {30       // TODO Auto-generated catch block31       e.printStackTrace();32     }finally{33       jdbc.close(conn, pstmt, result);34     }35     if(t1 != 0){36       t2=t2+1;37     }38     39     return t2;40   }41   42   /**43    * 查询指定页的数据44    * @param pageNo45    * @return46   */47   public List<User> listUser(int pageNo){48     PreparedStatement pstmt=null;49     ResultSet result=null;50     List<User> list=new ArrayList<User>();51     int pageSize=5;52     int page=(pageNo-1)*5;53     JDBCUtils jdbc=new JDBCUtils();54     Connection conn=jdbc.connect();55     String sql="select * from books order by id limit ?,?";56     try {57       pstmt=conn.prepareStatement(sql);58       pstmt.setInt(1, page);59       pstmt.setInt(2, pageSize);60       result=pstmt.executeQuery();61       while(result.next()){62         User user=new User();63         user.setId(result.getInt(1));64         user.setName(result.getString(2));65         user.setNumber(result.getString(3));66         list.add(user);67         68       }69     } catch (Exception e) {70       // TODO Auto-generated catch block71       e.printStackTrace();72     }finally{73       jdbc.close(conn, pstmt, result);74     }75     return list;76   }77 78 }

User 类用于存储查询到的数据,核心代码如下:

 1 public class User { 2   private int id; 3   private String name; 4   private String number; 5   public int getId() { 6     return id; 7   } 8   public void setId(int id) { 9     this.id = id;10   }11   public String getName() {12     return name;13   }14   public void setName(String name) {15     this.name = name;16   }17   public String getNumber() {18     return number;19   }20   public void setNumber(String number) {21     this.number = number;22   }23 }

 

2.控制层

ListUser 类内部调用 UserDao 对象查询数据并指派页面显示数据,核心代码如下:

 1 import java.io.IOException; 2 import java.io.PrintWriter; 3 import java.util.ArrayList; 4 import java.util.List; 5  6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 11 import com.dao.User;12 import com.dao.UserDao;13 14 public class ListUser extends HttpServlet {15   public ListUser() {16     super();17   }18 19   public void destroy() {20     super.destroy(); // Just puts "destroy" string in log21     // Put your code here22   }23 24   public void doGet(HttpServletRequest request, HttpServletResponse response)25       throws ServletException, IOException {26 27     doPost(request, response);28   }29 30   public void doPost(HttpServletRequest request, HttpServletResponse response)31       throws ServletException, IOException {32 33     34     response.setCharacterEncoding("utf-8");35     int pageNo = 1;36     UserDao userdao=new UserDao();37     List<User> lists=new ArrayList<User>();38     String pageno=request.getParameter("pageNos");39     if(pageno != null){40       pageNo=Integer.parseInt(pageno);41     }42     lists=userdao.listUser(pageNo);43     int recordCount=userdao.getPage();44     request.setAttribute("recordCount", userdao.getPage());45     request.setAttribute("listss", lists);46     request.setAttribute("pageNos", pageNo);47     request.getRequestDispatcher("userlist.jsp").forward(request, response);48   }49 50   public void init() throws ServletException {51     // Put your code here52   }53 54 }

 

3.表示层

输出页面 userlist.jsp ,使用 EL 和 JSTL 输出查询结果,核心代码如下:

 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>  4 <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> 5 <% 6 String path = request.getContextPath(); 7 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 8 %> 9 10 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">11 <html>12  <head>13   <base href="<%=basePath%>">14   15   <title>My JSP 'userlist.jsp' starting page</title>16   17   <meta http-equiv="pragma" content="no-cache">18   <meta http-equiv="cache-control" content="no-cache">19   <meta http-equiv="expires" content="0">  20   <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">21   <meta http-equiv="description" content="This is my page">22   <!--23   <link rel="stylesheet" type="text/css" href="styles.css">24   -->25 <style type="text/css">26 th,td{width: 150px;border: 2px solid gray;text-align: center;}27 body{text-align: center;}28 a{text-decoration: none;}29 table {border-collapse: collapse;}30 </style>31  </head>32  33  <body>34   <h2 align="center">图书信息</h2>35   <table align="center">36     <tr><td>书号</td><td>书名</td><td>库存量</td></tr>37   </table>38   <table align="center">39     <c:forEach items="${listss}" var="person">40     <tr>41     <td class="hidden-480">${person.id}</td>42     <td class="hidden-480">${person.name }</td>43     <td class="hidden-480">${person.number }</td>44     </tr>45     </c:forEach>46   </table>47   <br>48 49   <c:if test="${pageNos>1 }">50     <a href="ListUser?pageNos=1" >首页</a>51     <a href="ListUser?pageNos=${pageNos-1 }">上一页</a>52   </c:if>53   54    <c:if test="${pageNos <recordCount }">55     <a href="ListUser?pageNos=${pageNos+1 }">下一页</a>56     <a href="ListUser?pageNos=${recordCount }">末页</a>57   </c:if>58 59   <form action="ListUser">60   <h4 align="center">共${recordCount}页 &nbsp61   <input type="text" value="${pageNos}" name="pageNos" size="1">页62   <input type="submit" value="到达">63   </h4>64   </form>65  </body>66 </html>

 

4.效果图