好用的SSM框架——实现分页和搜索分页

分页是JAVA WEB项目常用的功能,昨天在Spring MVC中实现了简单的分页操作和搜索分页,在此记录一下。使用的框架为(MyBatis+SpringMVC+Spring)。


        首先我们需要一个分页的工具类:

1.分页

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

        有了这个工具类后,首先编写MyBatis的XxxxMapper.xml配置文件中的SQL语句,如下:

[html]  view plain  copy
  1. <!-- 分页SQL语句 -->  
  2. <select id="selectProductsByPage" resultMap="返回值类型">  
  3.   select   
  4.   *  
  5.   from 表名 WHERE user_id = #{userId,jdbcType=INTEGER} limit #{startPos},#{pageSize}   
  6. </select>  
  7. <!-- 取得记录的总数 -->  
  8. <select id="getProductsCount" resultType="long">  
  9.   SELECT COUNT(*) FROM 表名 WHERE user_id = #{userId,jdbcType=INTEGER}   
  10. </select>  


              此处我们可以看到,2个<select>需要分别传入3个和1个参数,此时在对应的DAO文件IXxxxDao中编写接口来编写对应的方法,方法名和mapper.xml中的id属性值一致:

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


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

[java]  view plain  copy
  1. /** 
  2.      * 分页显示商品 
  3.      * @param request 
  4.      * @param model 
  5.      * @param loginUserId 
  6.      */  
  7.     void showProductsByPage(HttpServletRequest request,Model model,int loginUserId);  

        接下来实现类中的方法就是要调用DAO层和接受Controller传入的参数,进行业务逻辑的处理,request用来获取前端传入的参数,model用来向JSP页面返回处理结果。

[java]  view plain  copy
  1. @Override  
  2. public void showProductsByPage(HttpServletRequest request, Model model,int loginUserId) {  
  3.     String pageNow = request.getParameter("pageNow");  
  4.   
  5.     Page page = null;  
  6.   
  7.     List<ProductWithBLOBs> products = new ArrayList<ProductWithBLOBs>();  
  8.   
  9.     int totalCount = (int) productDao.getProductsCount(loginUserId);  
  10.   
  11.     if (pageNow != null) {  
  12.         page = new Page(totalCount, Integer.parseInt(pageNow));  
  13.         allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId);  
  14.     } else {  
  15.         page = new Page(totalCount, 1);  
  16.         allProducts = this.productDao.selectProductsByPage(page.getStartPos(), page.getPageSize(), loginUserId);  
  17.     }  
  18.   
  19.     model.addAttribute("products", products);  
  20.     model.addAttribute("page", page);  
  21. }  


       接下来是控制器的编写,当用户需要跳转到这个现实产品的页面时,就需要经过这个控制器中相应方法的处理,这个处理过程就是调用业务层的方法来完成,然后返回结果到JSP动态显示,服务器端生成好页面后传给客户端(浏览器)现实,这就是一个MVC过程。

[java]  view plain  copy
  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.   
  17.     int loginUserId = loginUser.getUserId();  
  18.     //此处的productService是注入的IProductService接口的对象  
  19.     this.productService.showProductsByPage(request, model, loginUserId);  
  20.   
  21.     return "跳转到的JSP路径";  
  22. }  

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

[html]  view plain  copy
  1. <!-- 分页功能 start -->  
  2.     <div align="center">  
  3.         <font size="2">共 ${page.totalPageCount} 页</font> <font size="2">第  
  4.             ${page.pageNow} 页</font> <a href="myProductPage?pageNow=1">首页</a>  
  5.         <c:choose>  
  6.             <c:when test="${page.pageNow - 1 > 0}">  
  7.                 <a href="myProductPage?pageNow=${page.pageNow - 1}">上一页</a>  
  8.             </c:when>  
  9.             <c:when test="${page.pageNow - 1 <= 0}">  
  10.                 <a href="myProductPage?pageNow=1">上一页</a>  
  11.             </c:when>  
  12.         </c:choose>  
  13.         <c:choose>  
  14.             <c:when test="${page.totalPageCount==0}">  
  15.                 <a href="myProductPage?pageNow=${page.pageNow}">下一页</a>  
  16.             </c:when>  
  17.             <c:when test="${page.pageNow + 1 < page.totalPageCount}">  
  18.                 <a href="myProductPage?pageNow=${page.pageNow + 1}">下一页</a>  
  19.             </c:when>  
  20.             <c:when test="${page.pageNow + 1 >= page.totalPageCount}">  
  21.                 <a href="myProductPage?pageNow=${page.totalPageCount}">下一页</a>  
  22.             </c:when>  
  23.         </c:choose>  
  24.         <c:choose>  
  25.             <c:when test="${page.totalPageCount==0}">  
  26.                 <a href="myProductPage?pageNow=${page.pageNow}">尾页</a>  
  27.             </c:when>  
  28.             <c:otherwise>  
  29.                 <a href="myProductPage?pageNow=${page.totalPageCount}">尾页</a>  
  30.             </c:otherwise>  
  31.         </c:choose>  
  32.     </div>  
  33.     <!-- 分页功能 End -->  


2.查询分页

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

      这里给出控制器的代码作为参考:

[java]  view plain  copy
  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.   
  11.         String param = request.getParameter("param");  
  12.   
  13.         String condition = (String) session.getAttribute("condition");  
  14.   
  15.         //先判断SESSION中的condition是否为空  
  16.         if (condition == null) {  
  17.             condition = new String();  
  18.             session.setAttribute("condition", condition);  
  19.             //如果Session中的condition为空,再判断传入的参数是否为空,如果为空就跳转到搜索结果页面  
  20.             if (param == null || "".equals(param)) {  
  21.                 return "private/space/ProductSearchResult";  
  22.             }  
  23.         }  
  24.         //如果SESSION不为空,且传入的搜索条件param不为空,那么将param赋值给condition  
  25.         if (param != null && !("".equals(param))) {  
  26.             condition = param;  
  27.             session.setAttribute("condition", condition);  
  28.         }  
  29.         //使用session中的condition属性值来作为查询条件  
  30.         this.productService.showSearchedProductsByPage(request, model, condition);  
  31.   
  32.         return "跳转的页面";  
  33.     }  

猜你喜欢

转载自blog.csdn.net/qq_38659629/article/details/80529523