Universal Paging Hardcover Version
- Preface
- Ideas and Steps for Universal Paging
- Final results
- All required class structures and packages! [Insert picture description here] (Https://img-blog.csdnimg.cn/20200610235334613.png?X-oss-process=image/watermark, type_ZmFuZ3poZW5naGVpdGk, shadow_10, text_AHR0cHM6Ly9ibG9nLmNzG4ubmV0L21lbl9tYQ==, size_16, color_FFFFFF, t_70)
- Code Practice
- Database tables used
- 1. Entity ClassesBook.java
- 2. Common partsBaseDao.java
- 3. Write the dao layer (BookDao.java Inherit BaseDao)
- 4. Write Paging Tool Class (pageBean.java)
- 5. Encapsulate Paging Label Class (PageTag.java)
- 6. Processing business logicBookAction.java
- 7. Configure a character encoding filter (EncodingFiter.java)
- 8. Display PageBookList.jsp
Preface
Xiao Bian has explained the general paging in detail in the previous blog. Today, let's sort out the common paging in the first two blogs. Maybe many details are not repeated and verbose in this area, so friends you need are welcome to read them.
Links: General Paging (1) And General Paging (2).
It's important to comb business logic and put all the code together in this chapter
Ideas and Steps for Universal Paging
The text description of the preparation is described in the general page before, just look it up, this time start directly from the code
Final results
All required class structures and packages
Code Practice
Database tables used
1. Entity ClassesBook.java
package com.xiaoqing.entity; public class Book { private int bid; private String bname; private float price; @Override public String toString() { return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]"; } public int getBid() { return bid; } public void setBid(int bid) { this.bid = bid; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public Book() { } public Book(int bid, String bname, float price) { this.bid = bid; this.bname = bname; this.price = price; } }
2. Common partsBaseDao.java
package com.xiaoqing.dao; import java.lang.reflect.Field; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.xiaoqing.util.DBAccess; import com.xiaoqing.util.PageBean; public class BaseDao<T> { /*public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{ List<T> list=new ArrayList<T>(); Connection con=DBAccess.getConnection(); PreparedStatement ps = null; ResultSet rs = null; if(pageBean!=null&&!pageBean.isPagination()) { //Want to paginate-->List Requirements //Query out the total number of records that meet the criteria String countSql=getCountSql(sql); ps = con.prepareStatement(sql); rs = ps.executeQuery(); if(rs.next()) { pageBean.setTotal(rs.getLong(1)+ ""); } //Query out qualified result sets String pageSql=getPageSql(sql,pageBean); ps=con.prepareStatement(pageSql); rs=ps.executeQuery(); System.out.println(ps); //Show page breaks you want to see }else { //Don't want to paginate-->Drop-down box requirements ps = con.prepareStatement(sql); rs = ps.executeQuery(); System.out.println(ps); } T t;//To save memory, define outside of while while(rs.next()) { //list.add(new k(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price"))); *//** * Book b=new Book(); * b.setBid(rs.getInt("bid")); * b.setBname(rs.getString("bname")); * b.setPrice(rs.getFloat("price")); * list.add(b); * * Instantiate an object * Assign values to each attribute of this empty object * Return after adding the assigned object to the list collection *//* t =(T)clz.newInstance(); for (Field f : clz.getDeclaredFields()) { f.setAccessible(true); f.set(t, rs.getObject(f.getName())); } } DBAccess.close(con, ps, rs); return list; } */ public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{ Connection con = DBAccess.getConnection(); PreparedStatement pst = null; ResultSet rs = null; //Determine Paging if(pageBean!=null&&pageBean.isPagination()) { //List Requirements for ---, which you want to page //Query out the total number of records that meet the criteria String countSql=getCountSql(sql); //Re-execute countSql pst=con.prepareStatement(countSql); rs=pst.executeQuery(); if(rs.next()) { //Set Total Records pageBean.setTotal(rs.getLong(1)+ ""); } //Query out qualified result sets String pageSql=getPageSql(sql,pageBean); pst=con.prepareStatement(pageSql); rs=pst.executeQuery(); }else { //Do Not Want Paging --"Dropdown Box Requirements pst=con.prepareStatement(sql); rs=pst.executeQuery(); } List<T> list=new ArrayList<T>(); T t;//To save memory, define outside of while while(rs.next()) { /** * 1.Instantiate a book object (empty, not null) * 2.Take all the attributes of book and assign them values * 2.1 Get all property objects * 2.2 Assigning values to attribute objects * 3.The assigned book object is loaded in the list container */ //Reflection instantiation t =(T)clz.newInstance();//Equivalent to Book b=new Book(); //Reflect Get So Attribute Object Field[] fields = clz.getDeclaredFields(); //ergodic for (Field field : fields) { //Open Channel field.setAccessible(true); //Assigning values to attribute objects field.set(t, rs.getObject(field.getName())); } //Add Objects to Collection list.add(t); } DBAccess.close(con, pst, rs); return list; } public String getCountSql(String sql) { // TODO Auto-generated method stub return "select count(1) from ("+sql+") t"; } /** * sql=select * from t_mvc_book where true and bname like '%Sacred Ruins%';//Native sql * countSql=select count(1) from (select * from t_mvc_book where true and bname like '%Sacred Ruins%') * pageSql=select * from t_mvc_book where true and bname like '%Sacred Ruins%' limit 10,10; */ public String getPageSql(String sql,PageBean pageBean) { return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows(); } }
3. Write the dao layer (BookDao.java Inherit BaseDao)
package com.xiaoqing.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.xiaoqing.entity.Book; import com.xiaoqing.util.DBAccess; import com.xiaoqing.util.PageBean; import com.xiaoqing.util.StringUtils; public class BookDao extends BaseDao<Book> { //General query method modified by reflection public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{ String sql="select * from t_mvc_book where 1=1"; String bname=book.getBname(); if(StringUtils.isNotBlank(bname)) { sql+=" and bname like '%"+bname+"%'"; } return super.executeQuery(sql, Book.class, pageBean); } }
4. Write Paging Tool Class (pageBean.java)
package com.xiaoqing.util; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; /** * Paging Tool Class * */ public class PageBean { private int page = 1;// CurrentPage private int rows = 10;// Page Size private int total = 0;//Total Records //url of last query private String url; //Query criteria carried by the last query private Map<String, String[]> parameterMap=new HashMap<String, String[]>(); //Initialize pagebean s public void setRequest(HttpServletRequest req) { //Initialize the current page passed in from the jsp page this.setPage(req.getParameter("page")); //Initialize the page size passed in from the jsp page this.setRows(req.getParameter("rows")); //Initialize whether the jsp page was passed in or paginated this.setPagination(req.getParameter("pagination")); //Keep last query request this.setUrl(req.getRequestURL().toString()); //Keep previous query criteria this.setParameterMap(req.getParameterMap()); } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Map<String, String[]> getParameterMap() { return parameterMap; } public void setParameterMap(Map<String, String[]> parameterMap) { this.parameterMap = parameterMap; } private void setPage(String page) { if(StringUtils.isNotBlank(page)) { this.setPage(Integer.valueOf(page)); } } private void setRows(String rows) { if(StringUtils.isNotBlank(rows)) { this.setRows(Integer.valueOf(rows)); } } private void setPagination(String pagination) { //Only when the false string is filled in does it mean no paging this.setPagination(!"false".equals(pagination));; } private boolean pagination = true;// Paging or not public PageBean() { super(); } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public void setTotal(String total) { this.total = Integer.parseInt(total); } public boolean isPagination() { return pagination; } public void setPagination(boolean pagination) { this.pagination = pagination; } /** * Obtain subscript for start record * * @return */ public int getStartIndex() { return (this.page - 1) * this.rows; } @Override public String toString() { return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]"; } //Previous page public int getPrevPage() { return this.page>1?this.page-1:this.page; } //next page public int getNextPage() { return this.page<this.getMaxPage()?this.page+1:this.page; } //Maximum Page public int getMaxPage() { return this.total%this.rows==0?this.total/this.rows:(this.total/this.rows)+1; } }
5. Encapsulate Paging Label Class (PageTag.java)
package com.xiaoqing.tag; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.BodyTagSupport; import com.xiaoqing.util.PageBean; public class PageTag extends BodyTagSupport{ private static final long serialVersionUID = -258029245678348536L; private PageBean pageBean; public PageBean getPageBean() { return pageBean; } public void setPageBean(PageBean pageBean) { this.pageBean = pageBean; } @Override public int doStartTag() throws JspException { // TODO Auto-generated method stub JspWriter out = pageContext.getOut(); try { out.print(toHTML()); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } return super.doStartTag(); } private String toHTML() { // TODO Auto-generated method stub StringBuilder sb=new StringBuilder(); //HTML splicing of form form form from last query sb.append(" <form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>"); //Which page of data to look up sb.append(" <input type='hidden' name='page'>"); Map<String, String[]> parameterMap = pageBean.getParameterMap(); if(parameterMap.size()>0) { Set<Entry<String,String[]>> entrySet = parameterMap.entrySet(); for (Entry<String, String[]> entry : entrySet) { if(!"page".equals(entry.getKey())) { for (String val : entry.getValue()) { sb.append("<input type='hidden' value='"+val+"' name='"+entry.getKey()+"'>"); } } } } sb.append("</form> "); //Show the first 4 pages, the current page, and the last 5 by default int page=pageBean.getPage(); int max=pageBean.getMaxPage(); int before=page>4?4:page-1; int after=10-1-before;//5 after=max-page>after?after:max-page; //Used to control the click button effects of the previous page boolean startFlag=page>1; //Used to control the click button effects on the next page boolean endFlag=page<max; //Stitching Page Bars sb.append("<ul class='pagination'>"); sb.append("<li class='page-item "+(startFlag ? "" : "")+"'><a class='page-link' href='javascript:gotoPage(1)'>home page</a></li>"); sb.append("<li class='page-item "+(startFlag ? "" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getPrevPage()+")'><</a></li>"); //Represents the first four pages of the current page for (int i = before; i > 0 ; i--) { sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page-i)+")'>"+(page-i)+"</a></li>"); } sb.append("<li class='page-item active'><a class='page-link' href='javascript:gotoPage("+pageBean.getPage()+")'>"+pageBean.getPage()+"</a></li>"); //Represents the last 5 pages of the current page for (int i = 1; i <= after; i++) { sb.append("<li class='page-item'><a class='page-link' href='javascript:gotoPage("+(page+i)+")'>"+(page+i)+"</a></li>"); } sb.append("<li class='page-item "+(endFlag ? "" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getNextPage()+")'>></a></li>"); sb.append("<li class='page-item "+(endFlag ? "" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.getMaxPage()+")'>End Page</a></li>"); sb.append("<li class='page-item go-input'><b>To</b><input class='page-link' type='text' id='skipPage' name='' /><b>page</b></li>"); sb.append("<li class='page-item go'><a class='page-link' href='javascript:skipPage()'>Determine</a></li>"); sb.append("<li class='page-item'><b>common"+pageBean.getTotal()+"strip</b></li>"); sb.append("</ul>"); //js code for splicing pages sb.append("<script type='text/javascript'>"); sb.append("function gotoPage(page) {"); sb.append("document.getElementById('pageBeanForm').page.value = page;"); sb.append("document.getElementById('pageBeanForm').submit();"); sb.append("}"); sb.append("function skipPage() {"); sb.append("var page = document.getElementById('skipPage').value;"); sb.append("if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > '+max+') {"); sb.append("alert('Please enter 1~N Number');"); sb.append("return;"); sb.append("}"); sb.append("gotoPage(page);"); sb.append("}"); sb.append("</script>"); return sb.toString(); } }
6. Processing business logicBookAction.java
package com.xiaoqing.web; import java.io.IOException; import java.sql.SQLException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xiaoqing.dao.BookDao; import com.xiaoqing.entity.Book; import com.xiaoqing.util.PageBean; @WebServlet(name="book",urlPatterns="/book.action") public class BookAction extends HttpServlet{ private static final long serialVersionUID = 6817006004626927502L; private BookDao bookDao=new BookDao(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub Book book=new Book(); book.setBname(req.getParameter("bname")); PageBean pageBean=new PageBean(); pageBean.setRequest(req); try { List<Book> list = this.bookDao.list(book, pageBean); req.setAttribute("bookList", list); req.setAttribute("pageBean", pageBean); req.getRequestDispatcher("bookList.jsp").forward(req, resp); } catch (InstantiationException | IllegalAccessException | SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
7. Configure a character encoding filter (EncodingFiter.java)
package com.xiaoqing.util; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.ws.WebFault; /** * Chinese scrambling * */ @WebFilter(filterName="encodingFiter",urlPatterns="*.action") public class EncodingFiter implements Filter { private String encoding = "UTF-8";// Default Character Set public EncodingFiter() { super(); } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; // Chinese processing must be placed inChain.doFilter(request, response)Method front res.setContentType("text/html;charset=" + this.encoding); if (req.getMethod().equalsIgnoreCase("post")) { req.setCharacterEncoding(this.encoding); } else { Map map = req.getParameterMap();// Save all parameter names=parameter values(array)Of Map aggregate Set set = map.keySet();// Take out all parameter names Iterator it = set.iterator(); while (it.hasNext()) { String name = (String) it.next(); String[] values = (String[]) map.get(name);// Remove parameter value[Note: The parameter value is an array] for (int i = 0; i < values.length; i++) { values[i] = new String(values[i].getBytes("ISO-8859-1"), this.encoding); } } } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { String s = filterConfig.getInitParameter("encoding");// Xuan QianWeb.xmlThere is a lot of joy on the board if (null != s && !s.trim().equals("")) { this.encoding = s.trim(); } } }
8. Display PageBookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@taglib uri="/xiaoqing" prefix="z" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet"> <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Book Display</title> <style type="text/css"> .page-item input { padding: 0; width: 40px; height: 100%; text-align: center; margin: 0 6px; } .page-item input, .page-item b { line-height: 38px; float: left; font-weight: 400; } .page-item.go-input { margin: 0 10px; } </style> </head> <body> <form class="form-inline" action="${pageContext.request.contextPath }/book.action" method="post"> <div class="form-group mb-2"> <input type="text" name="bname" class="form-control-plaintext" id="staticEmail2" placeholder="Please enter a book name"> </div> <button type="submit" class="btn btn-primary mb-2">query</button> </form> <table class="table table-striped"> <thead> <tr> <th scope="col">Book Number</th> <th scope="col">Book Name</th> <th scope="col">Book Price</th> </tr> </thead> <tbody> <c:forEach var="b" items="${bookList }"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> </tr> </c:forEach> </tbody> </table> <z:page pageBean="${pageBean }"></z:page> </body> </html>
9. Additional StringUtils class
package com.xiaoqing.util; public class StringUtils{ // Private construction method to protect this class from being externally instantiated private StringUtils() { } /** * If the string equals null or after removing the space equals"",Returns true, otherwise returns false * * @param s * @return */ public static boolean isBlank(String s) { boolean b = false; if (null == s || s.trim().equals("")) { b = true; } return b; } /** * If the string is not equal to null or after space removal is not equal to"",Returns true, otherwise returns false * * @param s * @return */ public static boolean isNotBlank(String s) { return !isBlank(s); } }
OK, the whole process of universal paging is like this, this blog is not very detailed, need detailed general paging explanation in the blog before the small edition has records, do not understand welcome comments!!!
Thank you!!