After completing the small tasks left for myself, I feel that my understanding of paging is not very deep. I followed the school sister to learn paging, but I just copied all the code of the school sister directly and used it directly, and there is basically no correct code. Understand; this time, I used my own paging technology in the user management list I wrote. Although I still refer to the code of the original senior, but in a different way, I did not store the paging object in the session object like the senior. , paste the code below
The first is the paging interface, which is inherited by the Dao layer
package com.test.util; import com.test.entity.Users; import java.util.List; /** * @Description interface for paging, inherited by Dao layer, override these two methods * Created by sjz on 2016/9/19. */ public interface PageInterface { /** * Query all records, use some variables in the paging object to get * @param sPage * @return list */ public List<Users> findAll(SplitPage sPage); /** * Query the number of records * @return int */ public int getTotalRows(); }
The Dao layer rewrites two methods in the interface
@Override public List<Users> findAll(SplitPage sPage) { List<Users> list = new ArrayList<Users>(); ResultSet rs = null; try{ Class.forName(DRIVER); Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "SELECT * FROM t_users LIMIT ?,?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, sPage.getPageRow() * (sPage.getCurrentPage() - 1)); ps.setInt(2, sPage.getPageRow()); rs = ps.executeQuery(); while(rs.next()){ Users user = new Users(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); user.setContent(rs.getString("content")); user.setPhoto(rs.getString("photo")); list.add(user); } } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } return list; } @Override public int getTotalRows() { int totalRows = 0; try { Class.forName(DRIVER); Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "SELECT COUNT(*) FROM t_users"; PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while(rs.next()){ totalRows = rs.getInt(1); } } catch (ClassNotFoundException e) { e.printStackTrace (); } catch (SQLException e) { e.printStackTrace (); } return totalRows; }
Then there is the paging entity class, which is used to handle the jump between pages
package com.test.util; /** * Paging object * Created by sjz on 2016/9/19. */ public class SplitPage { public final static String FIRSTPAGE = "first";//首页 public final static String LASTPAGE = "last";//尾页 public final static String PREVIOUSPAGE = "previous";//上一页 public final static String NEXTPAGE = "next";//下一页 private int pageRow = 5;//Display 5 pieces of data per page private int totalRows = 0;//Number of data, provided by Dao private int currentPage = 1;//Current page private int firstPage = 1;//Home private int totalPage = 1;//Total number of pages public int getPageRow() { return pageRow; } public void setPageRow(int pageRow) { this.pageRow = pageRow; this.totalPage = this.totalRows / this.pageRow + ((this.totalRows % this.pageRow == 0) ? 0 : 1); } public int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; this.totalPage = this.totalRows/this.pageRow+((this.totalRows%this.pageRow==0)?0:1); } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getFirstPage() { return firstPage; } public void setFirstPage(int firstPage) { this.firstPage = firstPage; } public int getTotalPage () { return totalPage; } public int toNewPage(String flag) { //Get the number of pages for the next operation int newPage = this.currentPage;//Define the number of new pages as the current page if (flag != null && !"".equals(flag)) { //The request parameter is not empty if (SplitPage.FIRSTPAGE.equals(flag)) { //If the incoming parameter is the first page newPage = 1; //The number of new pages is the first page } else if (SplitPage.LASTPAGE.equals(flag)) { //If the passed parameter is the last page newPage = this.totalPage; //The number of new pages is the last page } else if (SplitPage.NEXTPAGE.equals(flag)) { //If the incoming parameter is the next page newPage = this.currentPage + ((this.currentPage == this.totalPage) ? 0 : 1);// If the current page is equal to the total number of pages, it will not go backward (+1) System.out.println(newPage); } else if (SplitPage.PREVIOUSPAGE.equals(flag)) { //If the incoming parameter is the previous page newPage = this.currentPage - ((this.currentPage == this.firstPage) ? 0 : 1);// If the current page is equal to the first page, it will not move forward (-1) } else { // passed in is a numeric string parameter //System.out.println(flag+"llll"); newPage = Integer.parseInt(flag.trim()); } } else {// The requested parameter is empty, the current page number remains unchanged newPage = this.currentPage; } this.setCurrentPage(newPage);// Remember to reset the current page return newPage; } }
Then there is the servlet, which just adds some passed parameters on the original basis, and changes the list method
package com.test.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import com.jspsmart.upload.File; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; import com.test.dao.UsersDao; import com.test.entity.Users; import com.test.util.SplitPage; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.PageContext; import static java.lang.System.out; /** * Created by sjz on 2016/9/14. */ public class UsersServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { doGet(request,response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); String method = request.getParameter("method"); out.println(method); switch (method){ case "insert" : insert(request,response); break; case "delete" : delete(request,response); break; case "toUpdate": int id3 = Integer.parseInt(request.getParameter("id")); Users user3 = UsersDao.selectById(id3); request.setAttribute("user",user3); request.getRequestDispatcher("../show.jsp").forward(request,response); case "update" : System.out.println(request.getPart("id")+"aaaa"); int id = Integer.parseInt(request.getParameter("id")); update(request,response,id); break; case "select" : //select(request,response); int id2 = Integer.parseInt(request.getParameter("id")); Users user2 = UsersDao.selectById(id2); request.setAttribute("user",user2); request.getRequestDispatcher("../show.jsp").forward(request,response); break; case "list" : //list(request,response);\ UsersDao uDao = new UsersDao (); SplitPage sPage = new SplitPage(); int totalRows = uDao.getTotalRows(); sPage.setTotalRows (totalRows); String flag = request.getParameter("flag"); String current = request.getParameter("current"); if(current!=null){ int currentPage = Integer.parseInt(current); sPage.setCurrentPage(currentPage); } int newPage = sPage.toNewPage(flag); List<Users> list = uDao.findAll(sPage); request.setAttribute("list",list); request.setAttribute("sPage",sPage); request.getRequestDispatcher("../list.jsp").forward(request,response); break; } } private void insert(HttpServletRequest request, HttpServletResponse response) { SmartUpload su = new SmartUpload(); JspFactory _jspxFactory = null; PageContext pageContext = null; _jspxFactory = JspFactory.getDefaultFactory(); pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true); try { su.initialize(pageContext); su.upload (); PrintWriter out = response.getWriter(); out.println("Upload" + su.save("picture") + "Successful files!!!"+"<br>"); String username = su.getRequest().getParameter("username"); String password = su.getRequest().getParameter("password"); String content = su.getRequest().getParameter("content"); File file = su.getFiles (). GetFile (0); if (file.isMissing()) System.out.println("No file selected"); String photo = file.getFileName(); String path = "/picture"; path = path + "/" + photo; file.saveAs(path, SmartUpload.SAVE_VIRTUAL); System.out.println(photo); Users user = new Users(); user.setUsername(username); user.setPassword(password); user.setContent(content); user.setPhoto(photo); if(UsersDao.insert(user)){ out.println("success"); response.setHeader("refresh", "3;UsersServlet?method=list&flag=first"); } else{ out.println("Failed"); response.setHeader("refresh", "3;UsersServlet?method=insert"); } } catch (ServletException e) { e.printStackTrace (); } catch (SmartUploadException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } private void delete(HttpServletRequest request, HttpServletResponse response) { int id = Integer.parseInt(request.getParameter("id")); try{ if(UsersDao.delete(id)){ out.println("success"); request.getRequestDispatcher("UsersServlet?method=list&flag=first").forward(request,response); } else{ out.println("Failed"); request.getRequestDispatcher("../list.jsp").forward(request,response); } } catch (ServletException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } private void update(HttpServletRequest request, HttpServletResponse response, int id) { SmartUpload su = new SmartUpload(); JspFactory _jspxFactory = null; PageContext pageContext = null; _jspxFactory = JspFactory.getDefaultFactory(); pageContext = _jspxFactory.getPageContext(this,request,response,"",true,8192,true); try { su.initialize(pageContext); su.upload (); PrintWriter out = response.getWriter(); out.println("Upload" + su.save("picture") + "Successful files!!!"+"<br>"); String username = su.getRequest().getParameter("username"); String password = su.getRequest().getParameter("password"); String content = su.getRequest().getParameter("content"); File file = su.getFiles (). GetFile (0); if (file.isMissing()) System.out.println("No file selected"); String photo = file.getFileName(); String path = "/picture"; path = path + "/" + photo; file.saveAs(path, SmartUpload.SAVE_VIRTUAL); System.out.println(photo); Users user = new Users(); user.setUsername(username); user.setPassword(password); user.setContent(content); user.setPhoto(photo); if(UsersDao.update(user,id)){ out.println("success"); response.setHeader("refresh", "3;UsersServlet?method=list&flag=first"); } else{ out.println("Failed"); response.setHeader("refresh", "3;UsersServlet?method=insert&flag=first"); } } catch (ServletException e) { e.printStackTrace (); } catch (SmartUploadException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } private void select(HttpServletRequest request, HttpServletResponse response) { } private void list(HttpServletRequest request, HttpServletResponse response) { } }
The last is list.jsp, which adds some code to better implement the function
<%@ page import="com.test.entity.Users" %> <%@ page import="java.util.List" %> <%@ page import="com.test.util.SplitPage" %><%-- Created by IntelliJ IDEA. User: lenovo Date: 2016/9/18 Time: 9:36 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>User List</title> </head> <body> <tr> <td>User ID</td> <td>Username</td> <td>User Profile</td> <td>Photo</td> </tr><br> <% SplitPage sPage = (SplitPage)request.getAttribute("sPage"); List<Users> list = (List<Users>) request.getAttribute("list"); for (int i=0;list!=null&&i<list.size();i++){ %> <tr> <td><%=list.get(i).getId()%></td> <td><%=list.get(i).getUsername()%></td> <td><%=list.get(i).getContent()%></td> <td><img src="../picture/<%=list.get(i).getPhoto()%>" style="width:100px;height:100px;"></td> <a href="UsersServlet?method=select&id=<%=list.get(i).getId()%>">修改</a> <a href="UsersServlet?method=delete&id=<%=list.get(i).getId()%>">删除</a> </tr> <br> <% } %> <div id="foot"> <a href="UsersServlet?method=list&flag=<%=SplitPage.FIRSTPAGE%>¤t=<%=sPage.getCurrentPage()%>">首页</a> <a href="UsersServlet?method=list&flag=<%=SplitPage.PREVIOUSPAGE%>¤t=<%=sPage.getCurrentPage()%>">上一页</a> <a href="UsersServlet?method=list&flag=<%=SplitPage.NEXTPAGE%>¤t=<%=sPage.getCurrentPage()%>">下一页</a> <a href="UsersServlet?method=list&flag=<%=SplitPage.LASTPAGE%>¤t=<%=sPage.getCurrentPage()%>">末页</a> <% for (int i = 1; i <= sPage.getTotalPage(); ++i) { //Control the total number of pages %> <a href="UsersServlet?method=list&flag=<%=i%>¤t=1"><%=i%></a> <% } %> </select> <label><%=sPage.getCurrentPage()%>/<%=sPage.getTotalPage()%>page<!-- current page/total page--> </label> </div> </body> </html>
In addition to these, all the other page jump addresses are followed by some parameters to modify the sPage object that is re-instantiated every time you visit, in order to achieve page jumps