在SSM中实现分页,可以采用mabatis分页插件,首先引入分页插件。
<!-- 引入分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency>
然后配置分页插件的相关配置
<plugins> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 使用下面的方式配置参数,后面会有所有的参数介绍,分页插件 --> <!-- <property name="param1" value="value1" /> --> <!-- 分页参数合理化,防止错误的页码数 --> <property name="reasonable" value="true"/> </plugin> </plugins>
在页面中采用如下调用方式
@RequestMapping("/emps") @ResponseBody public MSG getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) { // 这不是一个分页查询 // 引入pagehelper分页插件 // 在查询之前只需要调用传入页码,以及每页的大小 PageHelper.startPage(pn, 5); // startPage后面紧跟的这个查询就是一个分页查询 List<Employee> employees = employeeservice.getAll(); // 使用pageInfo包装查询后的结果,只需要将pageInfo交给页面 // 封装了详细的分页信息,包括我们查询出来的数据,连续传入5页 PageInfo page = new PageInfo(employees, 5); return MSG.success().add("pageInfo", page); }
最后采用模拟的MVC请求测试分页的正确性,代码如下
package com.zhang.test; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import com.github.pagehelper.PageInfo; import com.zhang.bean.Employee; /** * 使用Spring测试模块提供的测试请求功能,测试curd请求的正确性 * * @author Person * */ @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "classpath:applicationContext.xml", "file:src/main/webapp/WEB-INF/dispatcher-servlet.xml" }) public class MvcTest { //传入Springmvc的ioc @Autowired WebApplicationContext context; // 虚拟mvc请求,获取到处理结果 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,我们可以取出pageinfo进行验证 MockHttpServletRequest request=result.getRequest(); PageInfo pi=(PageInfo) request.getAttribute("pageInfo"); System.out.println("当前页码:"+pi.getPageNum()); System.out.println("总页码数:"+pi.getPages()); System.out.println("总记录数:"+pi.getTotal()); System.out.println("在页面中需要连续显示的页码"); int[] nums=pi.getNavigatepageNums(); for(int i:nums) { System.out.print(" "+i); } //获取员工数据 List<Employee> list=pi.getList(); for(Employee employee:list) { System.out.println("ID: "+employee.getdId()); } } }
测试数据如下