ssm分页查询
今天的主要任务是进行分页查询
在实际使用中,如果查询列表过长,不可能一次性的全部都显示出来,所以需要进行分页的操作。
参考分页简单制作 分页技术还区分两个:假分页和真分页
假分页:一次性从数据库读出表的所有数据一次性的返回给客户端,由js来控制每一页的显示。
真分页:由程序控制,每一次只返回一页大小的数据,显示到客户端。
由此可以很清楚的分辨出真假分页各自的优缺点:
假分页:由于一次性读出所有数据并返回给客户端,如果数据量庞大,所以这一次的动作可能是非常消耗服务器资源和带宽的,但是返回给客户端以后就非常轻松了,客户在一段时间内不会再像服务器端请求资源。但不代表可能出现一些意外情况,比如说客户将浏览器关闭,重新访问网站等。
真分页:假分页每次只取需要的数据返回给客户端,比起真分页没有那么大的数据库压力。但也因为这个工作特性,所以假分页的方法需要频繁和服务器端进行交互。既然频繁交互,自然也会给服务器带来负担。
本次采用的是假分页技术,分页查询:
a) 导架包
b) 写配置文件
c) 给service传 page(当前页页码), size(一页显示多少条),然后需要告诉serviceimpl 要开始用用分页啦
d) 在controller 传page, size,得到数据后传给pageInfo,最后返回到页面
本次需要的是写好的分页框架,首先是导架包:
在applicationContext.xml中导入配置:
<!-- 分页的配置信息 -->
<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>
在pom.xml中导入架包:
<!-- 分页架包 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
就可以使用封装好的分页配置,
之后是在service中给service传 page(当前页页码), size(一页显示多少条)。
注意,在UserDao中的函数依然是没有int page和int size参数的。
最后是在controller 传page, size,得到数据后传给pageInfo,最后返回到页面:
@Autowired
private UserService userService;
// 查询所有
@RequestMapping("/adfindAllUser.do")
public ModelAndView adfindAllUser(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "5") int size){
// 1. 调用service 去查询得到数据
List<User> userList = userService.adfindAllUser(page, size);
// 2. 把我们查到的数据存到分页里
PageInfo pageInfo = new PageInfo(userList);
// 3. 实例化 ModelAndView 对象,将得到的数据添加到里面
ModelAndView mv = new ModelAndView();
mv.addObject("pageInfo",pageInfo);
// user-list.jsp
mv.setViewName("user-manage");
return mv;
}
其中@RequestParam的作用是设置默认值,但是还有其他的很多用法,在这里不做详解。
将数据传到user-manage界面后,需要对原来的jsp进行修改:
首先是页面按钮的改动:
<div class="box-tools pull-right">
<ul class="pagination">
<li><a href="${pageContext.request.contextPath}/user/adfindAllUser.do?page=1&size=5" aria-label="Previous">首页</a></li>
<li><a href="${pageContext.request.contextPath}/user/adfindAllUser.do?page=${pageInfo.pageNum-1}&size=5">上一页</a></li>
<c:forEach begin="1" end="${pageInfo.pages}" var="pageNum">
<li><a href="${pageContext.request.contextPath}/user/adfindAllUser.do?page=${pageNum}&size=5">${pageNum}</a></li>
</c:forEach>
<li><a href="${pageContext.request.contextPath}/user/adfindAllUser.do?page=${pageInfo.pageNum+1}&size=5">下一页</a></li>
<li><a href="${pageContext.request.contextPath}/user/adfindAllUser.do?page=${pageInfo.pages}&size=5" aria-label="Next">尾页</a></li>
</ul>
</div>
显示用户的items也需要做出改动:
<c:forEach var="user" items="${pageInfo.list}">
<tr>
<td><input name="ids" type="checkbox"></td>
<td>${user.userId}</td>
<td>${user.username}</td>
<td>${user.userPassword}</td>
<td>${user.userStatus}</td>
<td class="text-center">
<a href="#" class="btn bg-olive btn-xs">封禁/解封</a>
<a href="#" class="btn bg-olive btn-xs">删除</a>
</td>
</tr>
</c:forEach>
效果如下: