基于ssm框架的mybatis pagehelper分页插件的使用
一、准备阶段
1、软件
eclipse,mysql数据库(用的oracle数据库的dept表的数据),maven。
2、maven环境下搭建好的ssm框架。
二、正题
1、maven的pom.xml中配置pagehelper,引入它的jar包
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
2、mabatis的主配置文件中配置pagehelper的拦截器
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
<property name="offsetAsPageNum" value="true"/>
<!-- rowBoundsWithCount设置为true时,使用 RowBounds 分页会进行 count 查询。 -->
<property name="rowBoundsWithCount" value="true"/>
<!-- pageSizeZero 为 true, 当 pageSize=0 或者 RowBounds.limit = 0 就会查询出全部的结果 -->
<property name="pageSizeZero" value="true"/>
<!-- reasonable 为 true,这时如果 pageNum<=0 会查询第一页,如果 pageNum>总页数 会查询最后一页 -->
<property name="reasonable" value="true"/>
<property name="returnPageInfo" value="check"/>
</plugin>
</plugins>
3、mybatis的mapper配置文件和接口中要有一个查询所有数据的方法,该怎么写就怎么写。
<select id="findall" resultType="Dept">
select * from Dept
</select>
public interface DeptDAO {
public List<Dept> findall()throws Exception;
}
4、对应的service也要有一个查询所有的方法
public List<Dept> findall() throws Exception {
List<Dept> list=deptdao.findall();
return list;
}
5、在action中写一个分页的方法
@RequestMapping(value="/finddept.do")
public String findByPage1(HttpServletRequest request,
@RequestParam(required=true,defaultValue="1") Integer pageNo,
@RequestParam(required=false,defaultValue="3") Integer pageSize)throws Exception{
PageHelper.startPage(pageNo, pageSize);
//紧跟着的第一个方法会被分页
List<Dept> list=deptservice.findall();
PageInfo<Dept> page=new PageInfo<Dept>(list);
request.setAttribute("list",list);
request.setAttribute("page",page);
return "dept";
}
6、在浏览器中请求http://localhost:8080/ssm001/finddept.do就可以了
7、实现简单的页面跳转
我用bootstrap简单的修饰了一下,其实都是超链接。此处只贴table和超链接部分
<table border="1" width="500">
<tr>
<td>部门编号</td>
<td>部门名称</td>
<td>部门地址</td>
<td>操作</td>
</tr>
<c:forEach items="${list}" var="d">
<tr>
<td>${d.deptno}</td>
<td>${d.dname}</td>
<td>${d.loc}</td>
<td><a href="deletedept.do?deptno=${d.deptno}" class="btn btn-primary">删除</a></td>
</tr>
</c:forEach>
</table>
<c:if test="${page.isFirstPage==true}">//是否为首页
<button class="btn btn-default btn-info disabled">首页</button>
<button class="btn btn-default btn-info disabled">上一页</button>
</c:if>
<c:if test="${page.isFirstPage!=true}">
<a href="finddept.do?pageNo=${page.firstPage}" class="btn btn-default btn-info">首页</a>
<a href="finddept.do?pageNo=${page.prePage}" class="btn btn-default btn-info">上一页</a>
</c:if>
<c:if test="${page.isLastPage==true}">//是否为尾页
<button class="btn btn-default btn-info disabled">下一页</button>
<button class="btn btn-default btn-info disabled">尾页</button>
</c:if>
<c:if test="${page.isLastPage!=true}">
<a href="finddept.do?pageNo=${page.nextPage}" class="btn btn-default btn-info">下一页</a>
<a href="finddept.do?pageNo=${page.lastPage}" class="btn btn-default btn-info">尾页</a>
</c:if>
说实话,pageInfo这个类是真好用,想用的,它里面都有。
差不多就这样了,毕竟不是搞前端的。
三、贴个pagehelper官方文档吧
有问题留言吧。撤了。