在编写Web后台代码时,分页是必不可少的,当然最通常的思路是在Sql中使用分页关键字来进行分页。在实际开发中,更多的是使用分页插件来减少代码冗杂,使编码更加清晰
思路:分页控制的代码写在拦截器中,从而不影响本来的业务逻辑代码(以PageHelper为例来讲述)
1.pom文件中引入分页插件的资源位置:
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>4.1.6version>
dependency>
2.在mybatis的spring配置文件中引入插件:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:com/ithaha/mapper/*.xml">property>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value>
dialect=mysql
reasonable=true
value>
property>
bean>
array>
property>
bean>
3.编写拦截器(规定以paging结尾的方法就是分页的方法,拦截controller层中以paging为结尾的方法)
@Aspect
@Component
public class PageInterceptor {
@Around("execution(* com.ithaha.controller..*.*Paging(..))")
public Object process(ProceedingJoinPoint point) throws Throwable {
Object[] args = point.getArgs();
if(args.length<2) {
//规定原方法的参数最后两个是当前页和每页条数
throw new Exception("参数不够分页");
}
PageHelper.startPage((Integer)args[args.length-2],(Integer)args[args.length-1]);
List list = (List) point.proceed();
PageInfo pageInfo = new PageInfo(list);
return pageInfo;
}
}
到此你已经编写出“万能”的分页插件了,只要你想分页,只需满足:1.方法名字以paging结尾 .2.方法参数最后两个是当前页和每页条数
为了看出效果,贴出controller层等相关代码
controller层:
//分页获取数据
@RequestMapping("/page")
@ResponseBody
public Object getUsersPaging(@RequestParam("currentPage")Integer currentPage,@RequestParam("size")Integer size) {
List<User> list = userService.getUsers();
return list;
}
以下是gerUsers()这个方法调用的sql
<select id="selectUsers" resultMap="BaseResultMap">
select "Base_Column_List" />
from user
select>
可以看出service,dao层的代码没有受到分页的任何影响.
总结:
1.pageHelper的安全性,当遇到pageHelper有效与否等问题时,查阅资料解决,由于这里只是简单使用,只是提一下
2.pageInfo这个类,可以看到,拦截分页方法最后返回的是pageInfo这个类的对象,他是里面的内容可以打印到前台看一下:
具体内容如下:
{"pageNum":1,"pageSize":3,"size":3,"orderBy":null,"startRow":1,"endRow":3,"total":6,"pages":2,"list":[{"id":1,"username":"jack","address":"kkkk"},{"id":2,"username":"rose","address":"jjjj"},{"id":3,"username":"wade","address":"3"}],"firstPage":1,"prePage":0,"nextPage":2,"lastPage":2,"isFirstPage":true,"isLastPage":false,"hasPreviousPage":false,"hasNextPage":true,"navigatePages":8,"navigatepageNums":[1,2]}
里面有很多对于前台来说有用的信息,所以直接返回他了