SSM项目手动分页详解

时间:2024-04-27 21:35:41

环境:idea+mysql

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

第一步,编写sql语句

  <select id="selectImages" resultType="com.abc.entity.Image_examine">
SELECT
*
FROM
image
<where>
<if test="status!=null and status!=''">
status=#{status}
</if>
<if test="examine!=null and examine!=''">
AND examine=#{examine}
</if>
<if test="sex!=null and sex!=''">
AND sex=#{sex}
</if>
</where>
limit #{start},#{pageSize}
</select>

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

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

第二步,编写controller

  /**
* @param examine 审核状态
* @param gender 性别
* @param request
* @return
*/
@RequestMapping(method = RequestMethod.GET, value = "/avatar")
public String selectAvatar(Integer examine, Integer gender,
HttpServletRequest request, Integer status,
Integer currentPage) {
try {
currentPage = (currentPage==null?1:currentPage);
int total = image_examineService.getCount();
int pageNum = 0;
if(total%100==0){
pageNum = total/100;
}else {
pageNum = total/100 + 1;
}
System.out.println("currentPage:"+currentPage+"total:"+total+"pageNum:"+pageNum); List<Image_examine> list = imageService.selectImages(status, examine == null ? 3 : examine,
gender,(currentPage-1)*100,100);
request.setAttribute("list", list);
复制代码是不对滴,自己敲~
request.setAttribute("pageNum",pageNum);
request.setAttribute("currentPage",currentPage);
} catch (Exception e) {
e.printStackTrace();
}
return "image";
}

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

  24行

    (currentPage-1)*100,100 这个在我转载的博客中有解释,即 limit后面的两个参数
  pageNum 意思是 数据一共多少页
  14-20行是计算多少页,获取pageNum,计算方式很简单 select count(1) from xxx 第三步,编写页面参数
  数据的遍历就不写了,直接写按钮
  
 <div class="btn-set">
<a class="pre" href="${pageContext.request.contextPath}/xx/avatar?currentPage=${currentPage-1}">上一页</a>
当前第<span class="currentPage">${currentPage}</span>页,共<span class="total">${pageNum}</span>页
<a class="next" href="${pageContext.request.contextPath}/xx/avatar?currentPage=${currentPage+1}">下一页</a>
</div>

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

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

  完事了~

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