SSM框架——实现分页和搜索分页

迷南。 2022-07-05 15:26 398阅读 0赞
  1. 分页是[Java ][Java]WEB项目常用的功能,昨天在[spring][] MVC中实现了简单的分页操作和搜索分页,在此记录一下。使用的框架为(MyBatis+SpringMVC+Spring)。
  2. 首先我们需要一个分页的工具类:

1.分页

[java] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. import java.io.Serializable;
  2. /**
  3. * 分页
  4. */
  5. public class Page implements Serializable {
  6. private static final long serialVersionUID = -3198048449643774660L;
  7. private int pageNow = 1; // 当前页数
  8. private int pageSize = 4; // 每页显示记录的条数
  9. private int totalCount; // 总的记录条数
  10. private int totalPageCount; // 总的页数
  11. @SuppressWarnings(“unused”)
  12. private int startPos; // 开始位置,从0开始
  13. @SuppressWarnings(“unused”)
  14. private boolean hasFirst;// 是否有首页
  15. @SuppressWarnings(“unused”)
  16. private boolean hasPre;// 是否有前一页
  17. @SuppressWarnings(“unused”)
  18. private boolean hasNext;// 是否有下一页
  19. @SuppressWarnings(“unused”)
  20. private boolean hasLast;// 是否有最后一页
  21. /**
  22. * 通过构造函数 传入 总记录数 和 当前页
  23. * @param totalCount
  24. * @param pageNow
  25. */
  26. public Page(int totalCount, int pageNow) {
  27. this.totalCount = totalCount;
  28. this.pageNow = pageNow;
  29. }
  30. /**
  31. * 取得总页数,总页数=总记录数/总页数
  32. * @return
  33. */
  34. public int getTotalPageCount() {
  35. totalPageCount = getTotalCount() / getPageSize();
  36. return (totalCount % pageSize == 0) ? totalPageCount
  37. : totalPageCount + 1;
  38. }
  39. public void setTotalPageCount(int totalPageCount) {
  40. this.totalPageCount = totalPageCount;
  41. }
  42. public int getPageNow() {
  43. return pageNow;
  44. }
  45. public void setPageNow(int pageNow) {
  46. this.pageNow = pageNow;
  47. }
  48. public int getPageSize() {
  49. return pageSize;
  50. }
  51. public void setPageSize(int pageSize) {
  52. this.pageSize = pageSize;
  53. }
  54. public int getTotalCount() {
  55. return totalCount;
  56. }
  57. public void setTotalCount(int totalCount) {
  58. this.totalCount = totalCount;
  59. }
  60. /**
  61. * 取得选择记录的初始位置
  62. * @return
  63. */
  64. public int getStartPos() {
  65. return (pageNow - 1) * pageSize;
  66. }
  67. public void setStartPos(int startPos) {
  68. this.startPos = startPos;
  69. }
  70. /**
  71. * 是否是第一页
  72. * @return
  73. */
  74. public boolean isHasFirst() {
  75. return (pageNow == 1) ? false : true;
  76. }
  77. public void setHasFirst(boolean hasFirst) {
  78. this.hasFirst = hasFirst;
  79. }
  80. /**
  81. * 是否有首页
  82. * @return
  83. */
  84. public boolean isHasPre() {
  85. // 如果有首页就有前一页,因为有首页就不是第一页
  86. return isHasFirst() ? true : false;
  87. }
  88. public void setHasPre(boolean hasPre) {
  89. this.hasPre = hasPre;
  90. }
  91. /**
  92. * 是否有下一页
  93. * @return
  94. */
  95. public boolean isHasNext() {
  96. // 如果有尾页就有下一页,因为有尾页表明不是最后一页
  97. return isHasLast() ? true : false;
  98. }
  99. public void setHasNext(boolean hasNext) {
  100. this.hasNext = hasNext;
  101. }
  102. /**
  103. * 是否有尾页
  104. * @return
  105. */
  106. public boolean isHasLast() {
  107. // 如果不是最后一页就有尾页
  108. return (pageNow == getTotalCount()) ? false : true;
  109. }
  110. public void setHasLast(boolean hasLast) {
  111. this.hasLast = hasLast;
  112. }
  113. }
  1. 有了这个工具类后,首先编写MyBatisXxxxMapper.xml配置文件中的SQL语句,如下:

[html] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. <**select id=”selectProductsByPage” resultMap=”返回值类型”>**
  2. select
  3. *
  4. from 表名 WHERE user_id = #{userId,jdbcType=INTEGER} limit #{startPos},#{pageSize}
  5. </**select**>
  6. <**select id=”getProductsCount” resultType=”long”>**
  7. SELECT COUNT(*) FROM 表名 WHERE user_id = #{userId,jdbcType=INTEGER}
  8. </**select**>
  1. 此处我们可以看到,2个<select>需要分别传入3个和1个参数,此时在对应的DAO文件IXxxxDao中编写接口来编写对应的方法,方法名和mapper.xml中的id属性值一致:

[java] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. /**
  2. * 使用注解方式传入多个参数,用户产品分页,通过登录用户ID查询
  3. * @param page
  4. * @param userId
  5. * @return startPos},#{pageSize}
  6. */
  7. public List selectProductsByPage(@Param(value=”startPos”) Integer startPos,@Param(value=”pageSize”) Integer pageSize,@Param(value=”userId”) Integer userId);
  8. /**
  9. * 取得产品数量信息,通过登录用户ID查询
  10. * @param userId
  11. * @return
  12. */
  13. public long getProductsCount(@Param(value=”userId”) Integer userId);

接口定义完成之后需要编写相应的业务接口和实现方法,在接口中定义这样一个方法,然后实现类中覆写一下:

[java] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. /**
  2. * 分页显示商品
  3. * @param request
  4. * @param model
  5. * @param loginUserId
  6. */
  7. void showProductsByPage(HttpServletRequest request,Model model,int loginUserId);
  1. 接下来实现类中的方法就是要调用DAO层和接受Controller传入的参数,进行业务逻辑的处理,request用来获取前端传入的参数,model用来向JSP页面返回处理结果。

[java] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. @Override
  2. public void showProductsByPage(HttpServletRequest request, Model model,int loginUserId) {
  3. String pageNow = request.getParameter(“pageNow”);
  4. Page page = null;
  5. List products = new ArrayList();
  6. int totalCount = (int) productDao.getProductsCount(loginUserId);
  7. if (pageNow != null) {
  8. page = new Page(totalCount, Integer.parseInt(pageNow));
  9. allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId);
  10. } else {
  11. page = new Page(totalCount, 1);
  12. allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId);
  13. }
  14. model.addAttribute(“products”, products);
  15. model.addAttribute(“page”, page);
  16. }
  1. 接下来是控制器的编写,当用户需要跳转到这个现实产品的页面时,就需要经过这个控制器中相应方法的处理,这个处理过程就是调用业务层的方法来完成,然后返回结果到JSP动态显示,服务器端生成好页面后传给客户端(浏览器)现实,这就是一个MVC过程。

[java] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. /**
  2. * 初始化 “我的产品”列表 JSP页面,具有分页功能
  3. *
  4. * @param request
  5. * @param model
  6. * @return
  7. */
  8. @RequestMapping(value = “映射路径”, method = RequestMethod.GET)
  9. public String showMyProduct(HttpServletRequest request, Model model) {
  10. // 取得SESSION中的loginUser
  11. User loginUser = (User) request.getSession().getAttribute(“loginUser”);
  12. // 判断SESSION是否失效
  13. if (loginUser == null || “”.equals(loginUser)) {
  14. return “redirect:/“;
  15. }
  16. int loginUserId = loginUser.getUserId();
  17. //此处的productService是注入的IProductService接口的对象
  18. this.productService.showProductsByPage(request, model, loginUserId);
  19. return “跳转到的JSP路径”;
  20. }

    1. JSP页面接受部分我就不写了,每个人都一样,也就是结合JSTLEL来写,(在循环输出的时候也做了判断,如果接受的参数为空,那么输出暂无商品,只有接受的参数不为空的时候,才循环输出,使用<<c:when test="$\{\}">结合<c:otherwise>),这里只给出分页的相关代码:

[html] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. <**div align=”center”>**
  2. <**font size=”2”>共 ${page.totalPageCount} 页</font> <**font size=”2”>
  3. ${page.pageNow} 页</**font**> <**a href=”myProductPage?pageNow=1”>首页</a>**
  4. <**c:choose**>
  5. <**c:when test=”${page.pageNow - 1 > 0}“>**
  6. <**a href=”myProductPage?pageNow=${page.pageNow - 1}“>上一页</a>**
  7. </**c:when**>
  8. <**c:when test=”${page.pageNow - 1 <= 0}“>**
  9. <**a href=”myProductPage?pageNow=1”>上一页</a>**
  10. </**c:when**>
  11. </**c:choose**>
  12. <**c:choose**>
  13. <**c:when test=”${page.totalPageCount==0}“>**
  14. <**a href=”myProductPage?pageNow=${page.pageNow}“>下一页</a>**
  15. </**c:when**>
  16. <**c:when test=”${page.pageNow + 1 < page.totalPageCount}“>**
  17. <**a href=”myProductPage?pageNow=${page.pageNow + 1}“>下一页</a>**
  18. </**c:when**>
  19. <**c:when test=”${page.pageNow + 1 >= page.totalPageCount}“>**
  20. <**a href=”myProductPage?pageNow=${page.totalPageCount}“>下一页</a>**
  21. </**c:when**>
  22. </**c:choose**>
  23. <**c:choose**>
  24. <**c:when test=”${page.totalPageCount==0}“>**
  25. <**a href=”myProductPage?pageNow=${page.pageNow}“>尾页</a>**
  26. </**c:when**>
  27. <**c:otherwise**>
  28. <**a href=”myProductPage?pageNow=${page.totalPageCount}“>尾页</a>**
  29. </**c:otherwise**>
  30. </**c:choose**>
  31. </**div**>

2.查询分页

  1. 关于**查询分页**,大致过程完全一样,只是第三个参数(上面是loginUserId)需要接受用户输入的参数,这样的话我们需要在控制器中接受用户输入的这个参数(页面中的<input>使用**GET方式传参)**,然后将其加入到SESSION中,即可完成查询分页(此处由于“下一页”这中超链接的原因,使用了不同的JSP页面处理分页和搜索分页,暂时没找到在一个JSP页面中完成的方法,出现了重复代码,这里的重复代码就是输出内容的那段代码,可以单独拿出去,然后用一个<include>标签加载到需要的JSP页面就可以了,这样可以避免代码重复):
  2. 这里给出控制器的代码作为参考:

[java] view plain copy

print ? 在CODE上查看代码片 派生到我的代码片

  1. /**
  2. * 通过 产品名称 查询产品
  3. * @param request
  4. * @param model
  5. * @return
  6. */
  7. @RequestMapping(value = “映射地址”, method = RequestMethod.GET)
  8. public String searchForProducts(HttpServletRequest request, Model model) {
  9. HttpSession session = request.getSession();
  10. String param = request.getParameter(“param”);
  11. String condition = (String) session.getAttribute(“condition”);
  12. //先判断SESSION中的condition是否为空
  13. if (condition == null) {
  14. condition = new String();
  15. session.setAttribute(“condition”, condition);
  16. //如果Session中的condition为空,再判断传入的参数是否为空,如果为空就跳转到搜索结果页面
  17. if (param == null || “”.equals(param)) {
  18. return “private/space/ProductSearchResult”;
  19. }
  20. }
  21. //如果SESSION不为空,且传入的搜索条件param不为空,那么将param赋值给condition
  22. if (param != null && !(“”.equals(param))) {
  23. condition = param;
  24. session.setAttribute(“condition”, condition);
  25. }
  26. //使用session中的condition属性值来作为查询条件
  27. this.productService.showSearchedProductsByPage(request, model, condition);
  28. return “跳转的页面”;
  29. }

发表评论

表情:
评论列表 (有 0 条评论,398人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SSM实现查询

    前言 > 分页基本上是我们项目中所必须的功能,当数据量过大时,可能会导致各种各样的问题发生,例如:服务器资源被耗尽,因数据传输量过大而使处理超时,等等。最终都会导致查询无

    相关 Layui + ssm

    做后台就会涉及到表格数据,当数据多的时候,就要使用分页来显示,这样就显得比较美观。分页确实有效,但它一定会加大系统的复杂度,如果数据量少的话可以不用分页,但是对于企业信息系统来

    相关 ssm查询

    引言:基于ssm框架下,利用Mybaits插件PageHelper进行分页查询,可以省去大量繁琐的代码,操作起来更为方便, 1、数据库表的设计 ![70][] ---