- 所需依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
2.xml配置分页助手
方式一:在Spring.xml文件中配置
<!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!--配置分页助手-->
<property name="plugins">
<array>
<!-- 引入插件类型 -->
<bean class="com.github.pagehelper.PageInterceptor">
<!-- 指定使用的数据库-->
<property name="properties">
<!--因为分页插件支持多种数据库,需指明当前所用数据库 ,helperDialect mysql数据库(方言)-->
<props>
<prop key="helperDialect">mysql</prop>
</props>
</property>
</bean>
</array>
</property>
<!-- 引入sqlMapConfig.xml文件 -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
<!-- 配置别名 -->
<property name="typeAliasesPackage" value="cn.hp.domain"></property>
</bean>
方式二:在mybatis.xml文件中配置
<configuration>
<plugins>
<!-- 引入分页插件,不用指定数据库方言,mybatis自动选择-->
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
3.编写service层
/**
* 分页助手
* @param currPage 当前页数
* @param pageSize 每页显示条数
* @return
*/
public PageInfo<Product> pageList02(Integer currPage, Integer pageSize) {
//指定分页参数
PageHelper.startPage(currPage,pageSize);
//获取所有记录 //findAll()方法为获取Product表中所有记录
List<Product> list = productMapper.findAll();
//创建PageInfo对象 参数一:表中所有记录 参数二要显示页码个数(如下图)
PageInfo<Product> pageInfo = new PageInfo<>(list,3);
return pageInfo;
}
4.编写controller层
@RequestMapping("/pageList")
public ModelAndView pageList(ModelAndView mv,
@RequestParam(name = "currPage",defaultValue = "1") Integer currPage,
@RequestParam(name = "pageSize",defaultValue = "5")Integer pageSize){
PageInfo<Product> pageInfo = productService.pageList02(currPage, pageSize);
mv.addObject("pageInfo",pageInfo);
mv.setViewName("product-list02");
return mv;
}
5.jsp页面片段
图中gotoPage为是自定义的方法