- 所需依賴
<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爲是自定義的方法