• J2EE基础-通用分页(2)


    目录

    前言

    一、改造pagebean

    分页核心思路

     PageBean类:

    新建一个 BookServlet :

    .jsp代码

    从Servlet运行结果:

    二、通用分页

    分页jsp:

    PageTag助手类:

    tld配置文件:

    优化PageBean:

    在bookList.jsp内导入y标签和c标签:

    优化BookServlet:

    再通过标签将数据遍历出来展示在页面上:

     中文乱码处理类:


    前言

    上次我们分享了通用分页的后台代码(http://t.csdn.cn/WaVH1),今天分享的内容通用分页的前端代码

    一、改造pagebean

    分页核心思路

     通过上图的得出一下思路

    1. 需要新增变量保存上一次查询条件
    2. 需要新增变量保存上一次请求地址:http://localhost:80/oyang_page/book/search
    3. 需要添加方法:获取最大页的页码
    4. 需要添加方法:获取下一页的页码
    5. 需要添加方法:获取上一页的页码
    6. 需要新增方法:初始化pagebean

     PageBean类:

    1. package com.oyang.util;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. import javax.servlet.http.HttpServletRequest;
    5. /**
    6. * 分页工具类
    7. *
    8. */
    9. public class PageBean {
    10. private int page = 1;// 页码
    11. private int rows = 10;// 页大小
    12. private int total = 0;// 总记录数
    13. private boolean pagination = true;// 是否分页
    14. // 需要新增变量保存上一次查询条件
    15. private Map<String, String[]> parameterMap=new HashMap<String,String[]>();
    16. // 需要新增变量保存上一次请求地址:http://localhost:80/oyang_page/book/search
    17. private String url;
    18. // 需要添加方法:获取最大页的页码
    19. public int maxPage() {
    20. return this.total%this.rows ==0?this.total /this.rows :this.total/this.rows+1;
    21. }
    22. // 需要添加方法:获取上一页的页码
    23. public int previousPage() {
    24. return this.page>1?this.page-1:this.page;
    25. }
    26. // 需要添加方法:获取下一页的页码
    27. public int nextPage() {
    28. return this.page<this.maxPage()?this.page+1:this.page;
    29. }
    30. // 需要新增方法:初始化pagebean
    31. public void serRequest(HttpServletRequest request) {
    32. this.setPage(request.getParameter("page"));
    33. this.setRows(request.getParameter("rows"));
    34. this.setPagination(request.getParameter("pagination"));
    35. this.setUrl(request.getRequestURL().toString());
    36. System.out.println(request.getRequestURL().toString());
    37. this.setParameterMap(request.getParameterMap());
    38. }
    39. private void setPagination(String pagination) {
    40. if(StringUtils.isNotBlank(pagination)) {
    41. this.setPagination("false".equals(pagination));
    42. }
    43. }
    44. private void setRows(String rows) {
    45. if(StringUtils.isNotBlank(rows)) {
    46. this.setRows(Integer.valueOf(rows));
    47. }
    48. }
    49. public void setPage(String page) {
    50. if(StringUtils.isNotBlank(page)) {
    51. //set自动生成的方法
    52. this.setPage(Integer.valueOf(page));
    53. }
    54. }
    55. public PageBean() {
    56. super();
    57. }
    58. public Map<String, String[]> getParameterMap() {
    59. return parameterMap;
    60. }
    61. public void setParameterMap(Map<String, String[]> parameterMap) {
    62. this.parameterMap = parameterMap;
    63. }
    64. public String getUrl() {
    65. return url;
    66. }
    67. public void setUrl(String url) {
    68. this.url = url;
    69. }
    70. public int getPage() {
    71. return page;
    72. }
    73. public void setPage(int page) {
    74. this.page = page;
    75. }
    76. public int getRows() {
    77. return rows;
    78. }
    79. public void setRows(int rows) {
    80. this.rows = rows;
    81. }
    82. public int getTotal() {
    83. return total;
    84. }
    85. public void setTotal(int total) {
    86. this.total = total;
    87. }
    88. public void setTotal(String total) {
    89. this.total = Integer.parseInt(total);
    90. }
    91. public boolean isPagination() {
    92. return pagination;
    93. }
    94. public void setPagination(boolean pagination) {
    95. this.pagination = pagination;
    96. }
    97. /**
    98. * 获得起始记录的下标
    99. *
    100. * @return
    101. */
    102. public int getStartIndex() {
    103. return (this.page - 1) * this.rows;
    104. }
    105. @Override
    106. public String toString() {
    107. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
    108. + ", parameterMap=" + parameterMap + ", url=" + url + "]";
    109. }
    110. }

    新建一个 BookServlet :

    1. package com.oyang.servlet;
    2. import java.io.IOException;
    3. import java.util.List;
    4. import java.util.Map;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import com.oyang.dao.BookDao;
    11. import com.oyang.entity.Book;
    12. import com.oyang.util.PageBean;
    13. @WebServlet("/book/search")
    14. public class BookServlet extends HttpServlet {
    15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16. doPost(request, response);
    17. }
    18. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19. PageBean pageBean=new PageBean();
    20. pageBean.serRequest(request);
    21. request.setAttribute("pageBean", pageBean);
    22. request.getRequestDispatcher("/bookList.jsp").forward(request, response);
    23. }
    24. }

    .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. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Insert title here</title>
    8. </head>
    9. <body>
    10. ${pageBean}
    11. </body>
    12. </html>

    Servlet运行结果:

     当我们能够拿到数据的时候改造就OK了

    二、通用分页

    分页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. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <link
    8. href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
    9. rel="stylesheet">
    10. <script
    11. src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
    12. <title>书籍列表</title>
    13. <style type="text/css">
    14. .page-item input {
    15. padding: 0;
    16. width: 40px;
    17. height: 100%;
    18. text-align: center;
    19. margin: 0 6px;
    20. }
    21. .page-item input, .page-item b {
    22. line-height: 38px;
    23. float: left;
    24. font-weight: 400;
    25. }
    26. .page-item.go-input {
    27. margin: 0 10px;
    28. }
    29. </style>
    30. </head>
    31. <body>
    32. <form class="form-inline"
    33. action="${pageContext.request.contextPath }/book.action" method="post">
    34. <div class="form-group mb-2">
    35. <input type="text" class="form-control-plaintext" name="bname"
    36. placeholder="请输入书籍名称">
    37. </div>
    38. <button type="submit" class="btn btn-primary mb-2">查询</button>
    39. </form>
    40. <table class="table table-striped ">
    41. <thead>
    42. <tr>
    43. <th scope="col">书籍ID</th>
    44. <th scope="col">书籍名</th>
    45. <th scope="col">价格</th>
    46. </tr>
    47. </thead>
    48. <tbody>
    49. <tr>
    50. <td>1</td>
    51. <td>圣墟第1章</td>
    52. <td>1</td>
    53. </tr>
    54. <tr>
    55. <td>1</td>
    56. <td>圣墟第1章</td>
    57. <td>1</td>
    58. </tr>
    59. </tbody>
    60. </table>
    61. </body>
    62. </html>

     目前我们的页面效果是这样的,数据暂时都是无效的定死的数据,并且无法查看上一页、下一页、尾页:所以我们还需要继续改写:

    PageTag助手类:

    1. package com.zking.tag;
    2. import java.io.IOException;
    3. import java.util.Map;
    4. import java.util.Map.Entry;
    5. import java.util.Set;
    6. import javax.servlet.jsp.JspException;
    7. import javax.servlet.jsp.JspWriter;
    8. import javax.servlet.jsp.tagext.BodyTagSupport;
    9. import com.oyang.util.PageBean;
    10. public class PageTag extends BodyTagSupport{
    11. private PageBean pageBean;
    12. public PageBean getPageBean() {
    13. return pageBean;
    14. }
    15. public void setPageBean(PageBean pageBean) {
    16. this.pageBean = pageBean;
    17. }
    18. @Override
    19. public int doStartTag() throws JspException {
    20. JspWriter out = pageContext.getOut();
    21. try {
    22. out.print(toHTML());
    23. } catch (Exception e) {
    24. // TODO Auto-generated catch block
    25. e.printStackTrace();
    26. }
    27. return super.doStartTag();
    28. }
    29. private String toHTML() {
    30. StringBuffer sb=new StringBuffer();
    31. //隐藏的form表达,作用保存上一次查询条件
    32. sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
    33. sb.append(" <input type='hidden' name='page' value=''>");
    34. Map<String, String[]> parameterMap = pageBean.getParameterMap();
    35. if(parameterMap!=null&&parameterMap.size()>0) {
    36. Set<Entry<String, String[]>> entrySet = parameterMap.entrySet();
    37. for (Entry<String, String[]> entry : entrySet) {
    38. String key=entry.getKey();//name/likes/page/rows
    39. String[] values = entry.getValue();
    40. if(!"page".equals(key)) {
    41. for (String value : values) {
    42. sb.append(" <input type='hidden' name='"+key+"' value='"+value+"'>");
    43. }
    44. }
    45. }
    46. }
    47. sb.append(" </form>");
    48. //分页条
    49. sb.append("<ul class='pagination justify-content-center'>");
    50. sb.append(" <li class='page-item "+(pageBean.getPage()==1? "disabled":"")+"'><a class='page-link'");
    51. sb.append(" href='javascript:gotoPage(1)'>首页</a></li>");
    52. sb.append(" <li class='page-item "+(pageBean.getPage()==1? "disabled":"")+"'><a class='page-link'");
    53. sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'>&lt;</a></li>");
    54. sb.append(" <li class='page-item'><a class='page-link' href='#'>1</a></li>");
    55. sb.append(" <li class='page-item'><a class='page-link' href='#'>2</a></li>");
    56. sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");
    57. sb.append(" <li class='page-item "+(pageBean.getPage()==pageBean.maxPage()? "disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>&gt;</a></li>");
    58. sb.append(" <li class='page-item "+(pageBean.getPage()==pageBean.maxPage()? "disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");
    59. sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link'");
    60. sb.append(" type='text' id='skipPage' name='' /><b>页</b></li>");
    61. sb.append(" <li class='page-item go'><a class='page-link'");
    62. sb.append(" href='javascript:skipPage()'>确定</a></li>");
    63. sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
    64. sb.append("</ul>");
    65. //分页jsp代码
    66. sb.append("<script type='text/javascript'>");
    67. sb.append(" function gotoPage(page) {");
    68. sb.append(" document.getElementById('pageBeanForm').page.value = page;");
    69. sb.append(" document.getElementById('pageBeanForm').submit();");
    70. sb.append(" }");
    71. sb.append(" function skipPage() {");
    72. sb.append(" var page = document.getElementById('skipPage').value;");
    73. sb.append(" if (!page || isNaN(page) || parseInt(page) < 1");
    74. sb.append(" || parseInt(page) > "+pageBean.maxPage()+") {");
    75. sb.append(" alert('请输入1~"+pageBean.maxPage()+"的数字');");
    76. sb.append(" return;");
    77. sb.append(" }");
    78. sb.append(" gotoPage(page);");
    79. sb.append(" }");
    80. sb.append(" </script>");
    81. return sb.toString();
    82. }
    83. }

    tld配置文件:

    1. <?xml version="1.0" encoding="UTF-8" ?>
    2. <taglib xmlns="http://java.sun.com/xml/ns/j2ee"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
    5. version="2.0">
    6. <description>JSTL 1.1 core library</description>
    7. <display-name>JSTL core</display-name>
    8. <tlib-version>1.1</tlib-version>
    9. <short-name>y</short-name>
    10. <uri>https://blog.csdn.net/weixin_65211978?type=blog</uri>
    11. <validator>
    12. <description>
    13. Provides core validation features for JSTL tags.
    14. </description>
    15. <validator-class>
    16. org.apache.taglibs.standard.tlv.JstlCoreTLV
    17. </validator-class>
    18. </validator>
    19. <tag>
    20. <name>page</name>
    21. <tag-class>com.zking.tag.PageTag</tag-class>
    22. <body-content>JSP</body-content>
    23. <attribute>
    24. <name>pageBean</name>
    25. <required>true</required>
    26. <rtexprvalue>true</rtexprvalue>
    27. </attribute>
    28. </tag>
    29. </taglib>

    优化PageBean:

    分页很多东西不用改变,但是其中有一个参数要变,那就是page(页数)

    1. package com.oyang.util;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. import javax.servlet.http.HttpServletRequest;
    5. /**
    6. * 分页工具类
    7. *
    8. */
    9. public class PageBean {
    10. private int page = 1;// 页码
    11. private int rows = 10;// 页大小
    12. private int total = 0;// 总记录数
    13. private boolean pagination = true;// 是否分页
    14. // 需要新增变量保存上一次查询条件
    15. private Map<String, String[]> parameterMap=new HashMap<String,String[]>();
    16. // 需要新增变量保存上一次请求地址:http://localhost:80/oyang_page/book/search
    17. private String url;
    18. // 需要添加方法:获取最大页的页码
    19. public int maxPage() {
    20. return this.total%this.rows ==0?this.total /this.rows :this.total/this.rows+1;
    21. }
    22. // 需要添加方法:获取上一页的页码
    23. public int previousPage() {
    24. return this.page>1?this.page-1:this.page;
    25. }
    26. // 需要添加方法:获取下一页的页码
    27. public int nextPage() {
    28. return this.page<this.maxPage()?this.page+1:this.page;
    29. }
    30. // 需要新增方法:初始化pagebean
    31. public void serRequest(HttpServletRequest request) {
    32. this.setPage(request.getParameter("page"));
    33. this.setRows(request.getParameter("rows"));
    34. this.setPagination(request.getParameter("pagination"));
    35. this.setUrl(request.getRequestURL().toString());
    36. System.out.println(request.getRequestURL().toString());
    37. this.setParameterMap(request.getParameterMap());
    38. }
    39. private void setPagination(String pagination) {
    40. if(StringUtils.isNotBlank(pagination)) {
    41. this.setPagination("false".equals(pagination));
    42. }
    43. }
    44. private void setRows(String rows) {
    45. if(StringUtils.isNotBlank(rows)) {
    46. this.setRows(Integer.valueOf(rows));
    47. }
    48. }
    49. public void setPage(String page) {
    50. if(StringUtils.isNotBlank(page)) {
    51. //set自动生成的方法
    52. this.setPage(Integer.valueOf(page));
    53. }
    54. }
    55. public PageBean() {
    56. super();
    57. }
    58. public Map<String, String[]> getParameterMap() {
    59. return parameterMap;
    60. }
    61. public void setParameterMap(Map<String, String[]> parameterMap) {
    62. this.parameterMap = parameterMap;
    63. }
    64. public String getUrl() {
    65. return url;
    66. }
    67. public void setUrl(String url) {
    68. this.url = url;
    69. }
    70. public int getPage() {
    71. return page;
    72. }
    73. public void setPage(int page) {
    74. this.page = page;
    75. }
    76. public int getRows() {
    77. return rows;
    78. }
    79. public void setRows(int rows) {
    80. this.rows = rows;
    81. }
    82. public int getTotal() {
    83. return total;
    84. }
    85. public void setTotal(int total) {
    86. this.total = total;
    87. }
    88. public void setTotal(String total) {
    89. this.total = Integer.parseInt(total);
    90. }
    91. public boolean isPagination() {
    92. return pagination;
    93. }
    94. public void setPagination(boolean pagination) {
    95. this.pagination = pagination;
    96. }
    97. /**
    98. * 获得起始记录的下标
    99. *
    100. * @return
    101. */
    102. public int getStartIndex() {
    103. return (this.page - 1) * this.rows;
    104. }
    105. @Override
    106. public String toString() {
    107. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
    108. + ", parameterMap=" + parameterMap + ", url=" + url + "]";
    109. }
    110. }

    在bookList.jsp内导入y标签和c标签:

    1. <%@taglib uri="https://blog.csdn.net/weixin_65211978?type=blog" prefix="y" %>
    2. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    优化BookServlet:

    1. package com.oyang.servlet;
    2. import java.io.IOException;
    3. import java.util.List;
    4. import java.util.Map;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import com.oyang.dao.BookDao;
    11. import com.oyang.entity.Book;
    12. import com.oyang.util.PageBean;
    13. @WebServlet("/book/search")
    14. public class BookServlet extends HttpServlet {
    15. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    16. doPost(request, response);
    17. }
    18. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    19. PageBean pageBean=new PageBean();
    20. pageBean.serRequest(request);
    21. BookDao bd=new BookDao();
    22. Book book=new Book();
    23. book.setBname(request.getParameter("bname"));
    24. try {
    25. List<Book> books = bd.list2(book, pageBean);
    26. request.setAttribute("books", books);
    27. } catch (Exception e) {
    28. // TODO Auto-generated catch block
    29. e.printStackTrace();
    30. }
    31. request.setAttribute("pageBean", pageBean);
    32. request.getRequestDispatcher("/bookList.jsp").forward(request, response);
    33. }
    34. }

    再通过标签将数据遍历出来展示在页面上:

    1. <c:forEach items="${books}" var="b">
    2. <tr>
    3. <td>${b.bid}</td>
    4. <td>${b.bname}</td>
    5. <td>${b.price}</td>
    6. </tr>
    7. </c:forEach>
    8. </tbody>
    9. </table>
    10. <y:page pageBean="${pageBean}"></y:page>

    结束完这些后你会发现,在查询的时候会出现乱码问题,这时候我们需要加上一个过滤器 

     中文乱码处理类:

    1. package com.oyang.util;
    2. import java.io.IOException;
    3. import java.util.Iterator;
    4. import java.util.Map;
    5. import java.util.Set;
    6. import javax.servlet.Filter;
    7. import javax.servlet.FilterChain;
    8. import javax.servlet.FilterConfig;
    9. import javax.servlet.ServletException;
    10. import javax.servlet.ServletRequest;
    11. import javax.servlet.ServletResponse;
    12. import javax.servlet.annotation.WebFilter;
    13. import javax.servlet.http.HttpServletRequest;
    14. import javax.servlet.http.HttpServletResponse;
    15. /**
    16. * 中文乱码处理
    17. *
    18. */
    19. @WebFilter("/book/*")
    20. public class EncodingFiter implements Filter {
    21. private String encoding = "UTF-8";// 默认字符集
    22. public EncodingFiter() {
    23. super();
    24. }
    25. public void destroy() {
    26. }
    27. public void doFilter(ServletRequest request, ServletResponse response,
    28. FilterChain chain) throws IOException, ServletException {
    29. HttpServletRequest req = (HttpServletRequest) request;
    30. HttpServletResponse res = (HttpServletResponse) response;
    31. // 中文处理必须放到 chain.doFilter(request, response)方法前面
    32. res.setContentType("text/html;charset=" + this.encoding);
    33. if (req.getMethod().equalsIgnoreCase("post")) {
    34. req.setCharacterEncoding(this.encoding);
    35. } else {
    36. Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
    37. Set set = map.keySet();// 取出所有参数名
    38. Iterator it = set.iterator();
    39. while (it.hasNext()) {
    40. String name = (String) it.next();
    41. String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
    42. for (int i = 0; i < values.length; i++) {
    43. values[i] = new String(values[i].getBytes("ISO-8859-1"),
    44. this.encoding);
    45. }
    46. }
    47. }
    48. chain.doFilter(request, response);
    49. }
    50. public void init(FilterConfig filterConfig) throws ServletException {
    51. String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
    52. if (null != s && !s.trim().equals("")) {
    53. this.encoding = s.trim();
    54. }
    55. }
    56. }

     OK,今日的学习就到此结束啦,如果对个位看官有帮助的话可以留下免费的赞哦(收藏或关注也行),如果文章中有什么问题或不足以及需要改正的地方可以私信博主,博主会做出改正的。个位看官,小陽在此跟大家说拜拜啦! 

  • 相关阅读:
    【AIGC未来的发展方向】面向人工智能的第一步,一文告诉你人工智能是什么以及未来的方向分析
    LeetCode笔记:Biweekly Contest 81
    Nacos 2.1.1 正式发布,微服务大变天
    大话STL第七期——stack栈
    2024年人工智能安全发展十大预测
    小试牛刀Linux信号
    Vue中的单向数据绑定和双向数据绑定到底是什么
    vscode中配置python环境
    基于RocketMQ实现分布式事务
    【FreeRTOS】15 空闲任务(实例:CPU利用率统计)
  • 原文地址:https://blog.csdn.net/weixin_65211978/article/details/125443238