SSM项目手动分页详解

环境:idea+mysql

  首先,既然是mysql,那肯定会用到limit,用这个分页的确很方便。

第一步,编写sql语句

 1  <select id="selectImages" resultType="com.abc.entity.Image_examine">
 2         SELECT
 3         *
 4         FROM
 5         image
 6         <where>
 7             <if test="status!=null and status!=''">
 8                 status=#{status}
 9             </if>
10             <if test="examine!=null and examine!=''">
11                 AND examine=#{examine}
12             </if>
13             <if test="sex!=null and sex!=''">
14                 AND sex=#{sex}
15             </if>
16         </where>
17         limit #{start},#{pageSize}
18     </select>

  注意这里的参数,start是查询的第几页[start是从0开始],pageSize是每页显示的数据量

  关于 当前页和下一页之间的规律关系,这里转载一篇博客,写的很详细。

第二步,编写controller

 1  /**
 2      * @param examine 审核状态
 3      * @param gender  性别
 4      * @param request
 5      * @return
 6      */
 7     @RequestMapping(method = RequestMethod.GET, value = "/avatar")
 8     public String selectAvatar(Integer examine, Integer gender,
 9                                HttpServletRequest request, Integer status,
10                                Integer currentPage) {
1112         try {
13             currentPage = (currentPage==null?1:currentPage);
14             int total = image_examineService.getCount();
15             int pageNum = 0;
16             if(total%100==0){
17                 pageNum = total/100;
18             }else {
19                 pageNum = total/100 + 1;
20             }
21             System.out.println("currentPage:"+currentPage+"total:"+total+"pageNum:"+pageNum);
22 
23             List<Image_examine> list = imageService.selectImages(status, examine == null ? 3 : examine,
24                     gender,(currentPage-1)*100,100);
25             request.setAttribute("list", list);
26             复制代码是不对滴,自己敲~
27             request.setAttribute("pageNum",pageNum);
28             request.setAttribute("currentPage",currentPage);
29             30         } catch (Exception e) {
31             e.printStackTrace();
32         }
33         return "image";
34     }

  参数列表   第10行  只需要关注 currentpage,这个是从页面获取到的,我们需要以这个数值来计算上下页。

  24行  

    (currentPage-1)*100,100 这个在我转载的博客中有解释,即 limit后面的两个参数
  pageNum 意思是 数据一共多少页
  14-20行是计算多少页,获取pageNum,计算方式很简单 select count(1) from xxx

第三步,编写页面参数
  数据的遍历就不写了,直接写按钮
  
1 <div class="btn-set">
2         <a class="pre" href="${pageContext.request.contextPath}/xx/avatar?currentPage=${currentPage-1}">上一页</a>
3         当前第<span class="currentPage">${currentPage}</span>页,共<span class="total">${pageNum}</span>4         <a class="next" href="${pageContext.request.contextPath}/xx/avatar?currentPage=${currentPage+1}">下一页</a>
5 </div>

  计算页数的加减,我推荐的做法是在页面计算,好处是controller只需要关心获取数据。

  如果在controller加减,就得给controller发送一个标识,告诉它我要进行什么操作,不方便。

  完事了~

  麋鹿留在最后的话:不要过分依赖插件,即使人家插件再好用,毕竟是人家写的,掌握核心才能不做代码的搬运工。

 
posted @ 2018-01-25 09:58  夜旦  阅读(540)  评论(0编辑  收藏  举报