中软国际实训记录(三)
昨天实现了ssm登录和基本的增删改查功能,今天我们继续进行学习,主要就是进行实现ssm分页和搜索功能的实现,这里只完成部分内容
1.实现对用户列分页式管理
实现分页式的管理我们需要对curd中进行微小修改,通过使用MyBatis的插件PageHelper进行分页,要在dependency之中添加依赖字段,具体如下:
dependency依赖修改
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
配置PageHelper
<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函数中加上两个int参数pages与size,用来标识页数以及每页长度,同时,需要在UserInfoServiceImpl中添加PageHelper.startPage(pages,size)来设定初始值
@Override
public List<UserInfo> findAll(int pages, int size){
PageHelper.startPage(pages, size);
return iUserInfoDao.findAll(pages, size);
}
并且在UserInfoController中建立一个PageInfo的对象,将获取到的用户表存储在里面,需要在pages与size前添加@RequestParam用来设定一个初始值
@RequestMapping("findAll.do")
public ModelAndView findAll(@RequestParam(defaultValue = "1") int pages, @RequestParam(defaultValue = "5") int size){
ModelAndView modelAndView = new ModelAndView();
List<UserInfo> userInfos = iUserInfoService.findAll(pages, size);
PageInfo users = new PageInfo(userInfos);
modelAndView.addObject("users",users);
modelAndView.setViewName("user-list");
return modelAndView;
}
修改user-list.jsp文件
<tbody>
<c:forEach var="user" items="${users.list}">
<tr>
<td><input name="ids" type="checkbox"></td>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td class="text-center">
<a href="${pageContext.request.contextPath}/user/toUpdate.do?id=${user.id}" class="btn bg-olive btn-xs">更新</a>
<a href="${pageContext.request.contextPath}/user/delete.do?id=${user.id}" class="btn bg-olive btn-xs">删除</a>
<a href="#" class="btn bg-olive btn-xs">添加角色</a>
</td>
</tr>
</c:forEach>
</tbody>
使用刚才创建的对象来进行数据传递,users.list来获取userinfo的信息
分页中还需确定分页的位置以及总共具有的页面
</div>
<!-- /.box-body -->
<div class="box-tools pull-right">
<ul class="pagination">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?pages=1&size=5" aria-label="Previous">首页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?pages=${users.pageNum-1}&size=5">上一页</a></li>
<c:forEach begin="1" end="${users.pages}" var="pageNumber">
<li><a href="${pageContext.request.contextPath}/user/findAll.do?pages=${pageNumber}&size=5">${pageNumber}</a></li>
</c:forEach>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?pages=${users.pageNum+1}&size=5">下一页</a></li>
<li><a href="${pageContext.request.contextPath}/user/findAll.do?pages=${users.pages}&size=5" aria-label="Next">尾页</a></li>
</ul>
</div>
</div>
2.结果
3.总结
这里对ssm有了初步的了解与认识,对查询的分页主要就是在dependency中添加PageHelp依赖,然后需要配置PageHelp,在使用的时候要用pages与size来确定页面与数据的量,使用jsp文件中封装好的PageInfo来传递数据供页面使用。