English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
front-end implementation uses ligerUI to implement pagination, it feels that using the framework is indeed simple, bored, and simulate the liger pagination interface (ignoring functionality and style)
Here we use the basic three-tier architecture+servlet+jsp implementation, the idea is very simple, write all pagination related information into a pagebean class, the service returns this bean class, and find the information from the bean every time the pagination query is performed. Just the details are more繁琐,such as boundary handling (front-end and back-end boundaries need to be handled), after the dropdown box jumps to display the current page, etc.
This is the pagination style implemented by ligerUI (the implementation process is described in my previous blog: https://pt.oldtoolbag.com/article/92850.htm)
simulation implementation process:
directory structure
model layer
a database corresponding model (Blog), and a pageBean (BlogPage)import java.sql.Date;
public class Blog { private int id; private int category_id; private String title; private String content; private Date created_time; getter and setter methods //@Override public String toString() { return "Blog [id=" id + category_id=" + " + category_id + "1#]", content=" + content + ", created_time=" + created_time + "]"; } }
public class BlogPage { private List<Blog> pagerecord;//Registros por página private int pageno;//Página atual private int pagenostart;//Índice de início da página por página private int pagesize=5;//Quantos dados por página private int totalrecord;//número total de registros private int totalpage;//Número total de páginas public BlogPage(int pageno,int totalrecord){ //pageno totalrecord podem ser informações existentes this.totalrecord=totalrecord; //Calcular o número total de páginas totalpage=(totalrecord%pagesize==0)?totalrecord/pagesize:totalrecord/pagesize+1; //Tratamento de limites de pageno if(pageno<=1) this.pageno=1; else if(pageno>=totalpage) this.pageno=totalpage; else this.pageno=pageno; //Calcular o índice de início da página por página, ou seja, o índice do primeiro dado da página, usado para consulta de paginação pagenostart=(this.pageno-1)*pagesize; } public int getPagenostart() { return pagenostart; } public void setPagenostart(int pagenostart) { this.pagenostart = pagenostart; } public List<Blog> getPagerecord() { return pagerecord; } public void setPagerecord(List<Blog> pagerecord) { this.pagerecord = pagerecord; } public int getPageno() { return pageno; } public void setPageno(int pageno) { this.pageno = pageno; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } 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; } }
camada de DAO
JDBCUtil encapsula as operações de conexão e liberação do jdbc
public class JDBCUtil { private static String url = "jdbc:mysql://localhost:3306/blogs_stu"; private static String username = "root"; private static String password = ""; static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection(){ Connection conn; try { conn= DriverManager.getConnection(url, username, password); return conn; } e.printStackTrace(); } return null; } public static void release(ResultSet rs,PreparedStatement ps,Connection conn){ if(rs!=null){ try { rs.close(); } e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } e.printStackTrace(); } } if(conn!=null){ try { conn.close(); } e.printStackTrace(); } } } }
public class BlogDao { //registros por página, passar o índice inicial da página e o tamanho da página para paginação, ou seja, os dois parâmetros de limit (usado para paginação no MySQL) public List<Blog> getPageRecord(int número da página inicial, int tamanho da página) { Connection conn = JDBCUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; String sql = "select * from blog limit ?,?"; List<Blog> list = new ArrayList<Blog>(); try { ps = conn.prepareStatement(sql); ps.setInt(1, número da página inicial); ps.setInt(2, tamanho da página); rs = ps.executeQuery(); while (rs.next()) { Blog blog = new Blog(); blog.setId(rs.getInt("id")); blog.setCategory_id(rs.getInt("category_id")); blog.setTitle(rs.getString("title")); blog.setContent(rs.getString("content")); blog.setCreated_time(rs.getDate("created_time")); list.add(blog); } return list; } e.printStackTrace(); } JDBCUtil.release(rs, ps, conn); } return null; } //número total de registros public int getTotal() { Connection conn = JDBCUtil.getConnection(); PreparedStatement ps = null; ResultSet rs = null; try { ps = conn.prepareStatement("select count(*) from blog); rs = ps.executeQuery(); if (rs.next()) { return rs.getInt(1; } } e.printStackTrace(); } JDBCUtil.release(rs, ps, conn); } return 0; } }
camada de serviço
public class BlogService { BlogDao blogDao = new BlogDao(); //Retorna pagebean, todas as informações necessárias para todas as páginas de navegação estão no pagebean public BlogPage findPageRecord(int pageno) { int totalrecord = blogDao.getTotal(); BlogPage blogpage = new BlogPage(pageno, totalrecord); List<Blog> list = blogDao.getPageRecord(blogpage.getPagenostart(),blogpage.getPagesize()); blogpage.setPagerecord(list); return blogpage; } }
classe servlet
@WebServlet("/BlogSplitServlet") public class BlogSplitServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html; charset=utf-8"); String pagenostr=request.getParameter("pageno"); //A primeira visita ao servletpagenostr é null, atribua um valor inicial, ou seja, o acesso à primeira página padrão int pageno=1; if(pagenostr!=null) pageno=Integer.parseInt(pagenostr); BlogService service=new BlogService(); BlogPage blogPage=service.findPageRecord(pageno); request.setAttribute("blogPage", blogPage); request.getRequestDispatcher("/blogPage.jsp"></forward(request, response);}} } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
So all pagination information is encapsulated into the pagebean
jsp implementation only needs to extract the information from the pagebean
Below is my jsp implementation (simulating ligerUI)
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@page import="java.util.*,model.Blog,model.BlogPage"%> !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Insert title here</title> <script type="text/javascript"> window.onload = function() { //Ensure that the select option matches the current page display select = document.getElementById("select"); pageno = '${blogPage.pageno}'; select.options[pageno - 1].selected = 'selected'; } //select下拉列表跳转 function selectjump() { var pageno = select.selectedIndex + 1; window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno=" + pageno; } //text jump, onblur event, input box loses focus function textjump() { var pageno = document.getElementById("text").value; window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno=" + pageno; } </script> </head> <body> <% BlogPage blogPage = (BlogPage) request.getAttribute("blogPage"); List<Blog> list = blogPage.getPagerecord(); // 尾页填充空白行,若不填充,尾页表格tr行数与前面不一致很难看 if (list.size() < blogPage.getPagesize()) { for (int i = list.size(); i < blogPage.getPagesize(); i++) list.add(null); } %> <div style="width: 50%; height: 400px"> <table border="1" cellspacing="0" width="100%" bgcolor="#CEF0C5"> <tr height="40px"> <td>id</td><td>Título</td><td>Conteúdo</td><td>Tempo de criação</td> </tr> <% for (Blog blog : list) { if (blog != null) { %> <tr height="50px"> <td width="10%"><%=blog.getId()%></td> <td width="20%"><%=blog.getTitle()%></td> <td width="40%"><%=blog.getContent()%></td> <td width="30%"><%=blog.getCreated_time()%></td> </tr> !-- Preenchimento de linha em branco na última página --> <%} else {%> <tr height="50px"> <td width="10%"></td> <td width="20%"></td> <td width="40%"></td> <td width="30%"></td> </tr> <%}}%> </table> <div style="height:50px;background-color: #4B7DB3;line-height: 40px;"> !-- Caixa de seleção --> <select id="select"> <%for (int i = 1; i <= blogPage.getTotalpage(); i++) {%> <option onclick="selectjump()"><%=i%></option> <%}%> </select> <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=1">Primeira Página</a> <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=<%=blogPage.getPageno()-1<1?blogPage.getPageno():blogPage.getPageno()-1%>">Anterior</a> <input type="text" id="text" size="1px" value="${blogPage.pageno}" onblur="textjump()">/${blogPage.totalpage} <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=<%=blogPage.getPageno()+1>blogPage.getTotalpage()?blogPage.getPageno():blogPage.getPageno()+1%>>Próxima página</a> <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=<%=blogPage.getTotalpage()%>>Última página</a> <div style="float: right;"> Mostra a partir de ${blogPage.pagenostart+1} até ${blogPage.pageno==blogPage.totalpage?blogPage.totalrecord:blogPage.pagesize}, Existem ${blogPage.totalrecord} itens. Mostra ${blogPage.pagesize} itens por página </div> </div> </div> </body> </html>
这是最后的样子,样式粗略的调了下,功能跟ligerUI默认的分页一模一样
将JSP中代码改为标签(JSTL,需引入相应的jar包)并将JSP中的尾页补白放在servlet中后
servlet中加入
// 尾页填充空白行,若不填充,尾页表格tr行数与前面不一致很难看 List<Blog> list = blogPage.getPagerecord(); if (list.size() < blogPage.getPagesize()) { for (int i = list.size(); i < blogPage.getPagesize(); i++) list.add(null); } blogPage.setPagerecord(list);
jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <%@page import="java.util.*,model.Blog,model.BlogPage"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> !DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Insert title here</title> <script type="text/javascript"> //select下拉列表跳转 function selectjump() { var select = document.getElementById("select"); var pageno = select.selectedIndex + 1; window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno=" + pageno; } //text跳转,onblur事件,输入框失去焦点时发生 function textjump() { var pageno = document.getElementById("text").value; window.location.href = "http://localhost/jspPageSplit/BlogSplitServlet?pageno=" + pageno; } </script> </head> <body> <div style="width: 50%; height: 400px"> <table border="1" cellspacing="0" width="100%" bgcolor="#CEF0C5"> <tr height="40px"> <td>id</td><td>Título</td><td>Conteúdo</td><td>Tempo de criação</td> </tr> <c:forEach items="${blogPage.pagerecord}" var="c" varStatus="vs"> <c:if test="${c!=null}"> <tr height="50px"> <td width="10%">${c.id}</td> <td width="20%">${c.title}</td> <td width="40%">${c.content}</td> <td width="30%">${c.created_time}</td> </tr> </c:if> !-- Preenchimento de linha em branco na última página --> <c:if test="${c==null}"> <tr height="50px"> <td width="10%"></td> <td width="20%"></td> <td width="40%"></td> <td width="30%"></td> </tr> </c:if> </c:forEach> </table> <div style="height:50px;background-color: #4B7DB3;line-height: 40px;"> !-- Caixa de seleção --> <select id="select"> <c:forEach begin="1" end="${blogPage.totalpage}" var="i"> <option value="${i}" onclick="selectjump()" ${blogPage.pageno==i?'selected="selected"':''}>${i}</option> </c:forEach> </select> <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=1">Primeira Página</a> <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=${blogPage.pageno-1<1?blogPage.pageno:blogPage.pageno-1}">Anterior</a> <input type="text" id="text" size="1px" value="${blogPage.pageno}" onblur="textjump()">/${blogPage.totalpage} <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=${blogPage.pageno+1>blogPage.totalpage?blogPage.pageno:blogPage.pageno+1}">Próxima página</a> <a href="${pageContext.request.contextPath}/BlogSplitServlet?pageno=${blogPage.totalpage}">Última página</a> <div style="float: right;"> Mostra a partir de ${blogPage.pagenostart+1} até ${blogPage.pageno==blogPage.totalpage?blogPage.totalrecord:blogPage.pagesize}, Existem ${blogPage.totalrecord} itens. Mostra ${blogPage.pagesize} itens por página </div> </div> </div> </body> </html>
Em aplicações práticas, você pode escrever páginas JSP conforme necessário, mas o código do back-end é basicamente genérico
Isso é tudo o que há no artigo, esperamos que ajude no seu aprendizado e que você apoie o tutorial Yell.
Declaração: O conteúdo deste artigo é extraído da Internet, pertence ao respectivo proprietário, é contribuído e carregado voluntariamente pelos usuários da Internet, o site não possui direitos de propriedade, não foi editado manualmente e não assume responsabilidade legal relevante. Se você encontrar conteúdo suspeito de violação de direitos autorais, por favor, envie e-mail para: notice#oldtoolbag.com (ao enviar e-mail, substitua # por @ para denunciar e forneça provas relevantes. Caso seja confirmado, o site deletará imediatamente o conteúdo suspeito de violação de direitos autorais.)