1、在pom.xml文件加入依赖
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.3</version>
</dependency>
2、在mybatis.xml内配置分页插件
<!--分页插件-->
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor">
</plugin>
</plugins>
applicationContext.xml中也必须读取mybatis文件,否则分页总是显示一页
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.ssm.domain"/>
<!--mapper.xml文件的位置(适用于接口与Mapper文件不在同一目录下)-->
<property name="mapperLocations" value="classpath:/mapper/*.xml"/>
<property name="configLocation" value="classpath:conf/mybatis.xml"/>
3、在Controller中使用分页插件
@RequestMapping("/emps")
public String getEmps(@RequestParam(value = "pn",defaultValue = "1")Integer pn, Model model){
//在查询之前调用,传入页码,以及每页的大小
Integer pageSize=5;
PageHelper.startPage(pn,pageSize);
List<Employee> emps=employeeService.getAll();
PageInfo page = new PageInfo(emps,5);
model.addAttribute("pageInfo",page);
return "list";
}
4、测试分页插件是否能使用----关于MockMvc的使用
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:conf/applicationContext.xml","file:F:\\IdeaProjects\\ssm\\src\\main\\resources\\conf\\applicationContext.xml"})
public class MvcTest {
@Autowired
WebApplicationContext context;
MockMvc mockMvc;
@Before
public void initMockMvc(){
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}
@Test
public void testPage() throws Exception{
//模拟请求拿到返回值
MvcResult result=mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pn","1")).andReturn();
//请求成功以后,从请求域中取出pageInfo验证
MockHttpServletRequest request = result.getRequest();
PageInfo page = (PageInfo) request.getAttribute("pageInfo");
System.out.println("当前页码:"+page.getPageNum());
System.out.println("总页码:"+page.getPages());
System.out.println("总记录数:"+page.getTotal());
System.out.println("连续显示页码:");
int[] nums = page.getNavigatepageNums();
for(int i:nums){
System.out.println(" "+i);
}
//获取员工数据
List<Employee> list = page.getList();
for(Employee employee:list){
System.out.println(" "+employee);
}
}
}