pagehelper有哪几步
在实际的项目开发中,常常需要使用到分页,分页方式分为两种:前端分页和后端分页。
-
前端分页
一次ajax请求数据的所有记录,然后在前端缓存并且计算count和分页逻辑,一般前端组件(例如dataTable)会提供分页动作。
特点是:简单,很适合小规模的web平台;当数据量大的时候会产生性能问题,在查询和网络传输的时间会很长。 -
后端分页
在ajax请求中指定页码pageNum和每页的大小pageSize,后端查询出当页的数据返回,前端只负责渲染。
特点是:复杂一些;性能瓶颈在MySQL的查询性能,这个当然可以调优解决。一般来说,开发使用的是这种方式。
一、 在pom.xml中配置PageHelper的依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
</dependencies>
二、在applicationContext中配置
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<props>
<prop key="helperDialect">mysql</prop>
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
三、修改之前的findAll方法添加传入的值
public List<User> findAll(int page,int size)
//controller
@RequestMapping("/findAll.do")
private ModelAndView findAll(@RequestParam(defaultValue = "1") int page,@RequestParam(defaultValue = "4") int size){
List<User> userList = userService.findAll(page,size);
PageInfo pageInfos=new PageInfo(userList);
ModelAndView mv=new ModelAndView();
mv.setViewName("user-list");
mv.addObject("pageInfos",pageInfos); //将pageinfos添加到mv中
return mv; // spring MVC通过ModelAndView 对象把模型和视图结合在一起
}
//分页
<div class="box-tools pull-right">
<ul class="pagination">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=1&size=5" aria-label="Previous">首页 </a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${ps.pageNum-1}&size=5">上一页</a></li>
<c:forEach begin="1" end="${ps.pages}" var="pageNum">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${pageNum}&size=5">${pageNum}</a></li>
</c:forEach>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${ps.pageNum+1}&size=5">下一页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?page=${ps.pages}&size=5" aria-label="Next">尾页</a></li>
</ul>
</div>
更新操作
mapper:
<select id="selectByID" resultType="com.zhongruan.bean.UserInfo" parameterType="int">
select * from userinfo where id=#{id}
</select>
<update id="update" parameterType="com.zhongruan.bean.UserInfo">
update userinfo set username=#{username},password=#{password} where id=#{id}
</update>
Controller:
@RequestMapping("toUpdate.do")
public ModelAndView toUpdate(int id){
System.out.println("a a a a a");
UserInfo userInfo= userInfoService.selectByID(id);
System.out.println("a a a a");
userInfo.toString();
System.out.println("a a a");
ModelAndView mv=new ModelAndView();
mv.addObject("userInfo",userInfo);
mv.setViewName("user-update");
return mv;
}
@RequestMapping("update.do")
public String update(UserInfo userInfo){
userInfoService.update(userInfo);
return "redirect:findAll.do";
}