查询及测试——后台分页展示
1、访问index.jsp页面
2、index.jsp发出查询员工列表请求
3、EmployeeController来接受请求,查出员工数据
4、来到list.jsp页面进行展示
实现:
URL:/emps
(1).index.jsp页面添加
<jsp:forward page="/emps"></jsp:forward>
(2).新建一个EmployeeController控制器
(3).新建一个EmployeeService,其有一个getAll()方法,返回所有员工
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
//查询员工数据(未分页查询)
@RequestMapping("/emps")
public String getEmps() {
List<Employee> emps = employeeService.getAll();
return "list";
}
}
(4).EmployeeService 层中需要有dao层的业务逻辑,故新建一个employeeMapper来实现getAll()方法;
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
public List<Employee> getAll() {
// TODO Auto-generated method stub
return employeeMapper.selectByExampleWithDept(null);
}
}
(5).实现分页查询
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
//查询员工数据(分页查询)
@RequestMapping("/emps")
public String getEmps(@RequestParam(value="pn",defaultValue="1")Integer pn,Model model) {//1.设置参数
//2.引入PageHelper分页插件(使用细节看官方文档)
//在查询之前只需调用下面,并传入页码,以及每页的大小
PageHelper.startPage(pn, 5);
//startPage后面紧跟的查询就是一个分页查询
List<Employee> emps = employeeService.getAll();
//,使用pageinfo包装查询后的结果,只需要将pageinfo交给页面即可
//,封装了详细的分页信息,包括有我们查询出来的数据,传入连续显示的页数
PageInfo page = new PageInfo(emps,5);
model.addAttribute("pageInfo",page );
return "list";
}
}
单元测试:
/*
* 使用Spring测试模块提供的测试请求功能,测试crud请求的正确性
*
* */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration //需要添加这个注解才能自动注入IOC容器,即WebApplicationContext context
@ContextConfiguration(locations= {"classpath:applicationContext.xml","file:src/main/webapp/WEB-INF/dispatcherServlet-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", "10")).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);
}
System.out.println("");
//获取员工数据
List<Employee> list = pi.getList();
for (Employee employee : list) {
System.out.println("ID:"+employee.getEmpId()+"==>Name:"+employee.getEmpName());
}
}
}
测试结果
过程:
进入首页→转到emps请求→controller收到请求,查询出所有员工数据以及分页信息→转到list页面,展示员工列表