原文再续,书接上回。今天我们来实现员工查询的前后端代码。
首先实现我们的后端代码,在com.sunsy.crud.service包下创建EmployeeService类,在里边实现一个查询所有员工的方法,如下(有些关键的方法是啥意思我都写到注释里了):
package com.sunsy.crud.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sunsy.crud.bean.Employee;
import com.sunsy.crud.dao.EmployeeMapper;
@Service
public class EmployeeService {
@Autowired
EmployeeMapper employeeMapper;
/**
* 查询所有信息
* @return
*/
public List<Employee> getAll(){
return employeeMapper.selectByExampleWithDept(null);
}
}
接下来我们在com.sunsy.crud.controller包下创建EmployeeController类,里边调用EmployeeService以及开源的PageHelper插件实现分页查询,并将结果放到model里传给list页面,代码如下:
package com.sunsy.crud.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sunsy.crud.bean.Employee;
import com.sunsy.crud.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
/**
* 分页查询所有员工信息
* @return
*/
@RequestMapping("/emps")
public String getEmps(@RequestParam(value="pageNum", defaultValue="1")Integer pageNum, Model model) {
//引入分页插件pagehelper
//在startPage后的第一个查询会变成分页查询
PageHelper.startPage(pageNum, 5);
List<Employee> emps = employeeService.getAll();
//把查询结果放到pageInfo里,这个pagehelper提供的类很好用,封装了各种我们需要的信息,那个5代表连续现实的页数
PageInfo<Employee> page = new PageInfo<Employee>(emps, 5);
//把pageinfo放到model里,这样就会传给界面
model.addAttribute("pageInfo", page);
return "list";
}
}
有一点必须要记得,按PageHelper的帮助文档上所说,如果想要使用它,必须在mybatis的主配置文件,也就是我们的mybatis-config.xml里配置plugin interceptor,完整的mybatis-config.xml配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 驼峰命名规则 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<typeAliases>
<!-- 批量定义别名(别名为实体类下的类名,第一个字母大小写都可以) -->
<package name="com.sunsy.crud.bean"/>
</typeAliases>
<plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>
</configuration>
接下来,我们还是先测试一下我们写的这个controller能不能用,在com.sunsy.crud.test包下创建MvcTest类,代码如下:
package com.sunsy.crud.test;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.PageInfo;
import com.sunsy.crud.bean.Employee;
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations= {"classpath:applicationContext.xml", "file:src/main/webapp/WEB-INF/dispatcherServlet-servlet.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("pageNum", "9")).andReturn();
//请求成功后,返回值中会有pageInfo
// HttpServletRequest request = result.getRequest();
// PageInfo pageInfo = (PageInfo) request.getAttribute("pageInfo");
//也可以直接从result中获取model,再从model里获取pageInfo,效果和上边注释的代码一样
ModelAndView model = result.getModelAndView();
Map<String, Object> modelAndView = model.getModel();
PageInfo pageInfo = (PageInfo) modelAndView.get("pageInfo");
System.out.println("当前页码:" + pageInfo.getPageNum());
System.out.println("总页码:" + pageInfo.getPages());
System.out.println("总记录数:" + pageInfo.getTotal());
System.out.println("在页面连续显示的页码");
int[] numbers = pageInfo.getNavigatepageNums();
for(int i:numbers) {
System.out.print(i+" ");
}
//获取员工数据
List<Employee> list = pageInfo.getList();
for(Employee emp: list) {
System.out.println("ID:" + emp.getEmpId() + " Name:" + emp.getEmpName() + " deptName:" + emp.getDepartment().getDeptName());
}
}
}
run As JUnittest,理论上应该是能成功的,反正我的是OK的。。。。。好了,到此为止查询所有员工信息的后端代码就完成了,接下来我们就要编写前端代码了。
首先,因为我们的controller里的方法返回list,也就是说我们要在Webapp/WEB-INF/views下创建一个list.jsp文件,这样方法才能跳转过去,至于为啥在这个路径下创建,因为我们在第二章编写MVC的配置文件dispatcherServlet-servlet.xml时已经配置过了。好了,直接上list.jsp代码了,里边东西很多(不过关于bootstrap的东西我都是从官网上拷的,bootstrap官网写的十分详细,还是中文的,很容易就能找到我们想要的效果),我尽量把关键的东西都写到注释里了,希望能对大家有点帮助,代码如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>员工列表</title>
<!-- 找到web项目的webapp路径 -->
<%
pageContext.setAttribute("APP_PATH", request.getContextPath());
%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<script type="text/javascript" src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
<link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
<script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<!-- 搭建显示页面 -->
<div class="container">
<!-- 标题 -->
<div class="row">
<div class="col-md-12">
<h1>SSM-CRUD</h1>
</div>
</div>
<!-- 删除和新增两个按钮 -->
<div class="row">
<div class="col-md-4 col-md-offset-8">
<button class="btn btn-success">新增</button>
<button class="btn btn-danger">删除</button>
</div>
</div>
<!-- 员工数据在表格中显示 -->
<div class="row">
<div class="col-md-12">
<table class="table table-hover">
<tr>
<th>#</th>
<th>empName</th>
<th>gender</th>
<th>email</th>
<th>departName</th>
<th>操作</th>
</tr>
<c:forEach items="${pageInfo.list}" var="emp">
<tr>
<th>${emp.empId }</th>
<th>${emp.empName }</th>
<th>${emp.gender=="M"?"男":"女" }</th>
<th>${emp.email }</th>
<th>${emp.department.deptName }</th>
<th>
<button class="btn btn-primary btn-sm">
编辑
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
</button>
<button class="btn btn-danger btn-sm">
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
删除
</button>
</th>
</tr>
</c:forEach>
</table>
</div>
</div>
<!-- 显示分页信息 -->
<div class="row">
<div class="col-md-6">
当前${pageInfo.pageNum }页,总${pageInfo.pages }页,总${pageInfo.total }条记录
</div>
<div class="col-md-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<li><a href="${APP_PATH }/emps?pageNum=1">首页</a></li>
<c:if test="${pageInfo.hasPreviousPage }">
<li>
<a href="${APP_PATH }/emps?pageNum=${pageInfo.pageNum-1}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach items="${pageInfo.navigatepageNums }" var="numbers">
<c:if test="${numbers==pageInfo.pageNum }">
<li class="active"><a href="#">${numbers }</a></li>
</c:if>
<c:if test="${numbers!=pageInfo.pageNum }">
<li><a href="${APP_PATH }/emps?pageNum=${numbers }">${numbers }</a></li>
</c:if>
</c:forEach>
<c:if test="${pageInfo.hasNextPage }">
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li><a href="${APP_PATH }/emps?pageNum=${pageInfo.pages}">尾页</a></li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
OK,这就算是大功告成了,run on server启动项目,进浏览器看一下效果吧:
虽然效果已经出来了,但是说实话,现在大家开发写controller的方法的时候,一般都是返json字符串(这样可以更好的前后端分离,但是实际上,我没见过多少前端去写jsp或者thymeleaf的。。。),已经很少有把内容写到model里的了,所以下一次我们会用返回json的方式实现和上边相同的效果,紧跟潮流。
好了,这一讲到此结束,预知后事如何,且听下回分解。