1 环境搭建
1 创建web工程,导入以下jar包
2 配置web.xml文件
- 配置过滤器CharacterEncodingFilter
- 配置前端控制器DispacherServlet
- 配置过滤器HiddenHttpMethodFilter
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置CharacterEncodingFilter过滤器,解决POST请求中文乱码问题
注意:该过滤器一定要配置到最上面
-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--设置属性encoding的值-->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
<!--设置属性forceRequestEncoding的值-->
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置DispatcherServlet的初始化參數:设置SpringMVC文件的路径和文件名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置HiddenHttpMethodFilte过滤器,目的是为了将POST请求转换为PUT或DELETE请求-->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3 创建SpringMVC的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--配置自动扫描的包-->
<context:component-scan base-package="com.springmvc.crud"></context:component-scan>
<!--配置视图解析器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--配置前缀-->
<property name="prefix" value="/WEB-INF/views/"></property>
<!--配置后缀-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置处理静态资源-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<!--配置了处理静态资源之后也需要配置以下标签-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
4 创建实体类和Dao
1) 实体类
a) Employee
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Employee(Integer id, String lastName, String email, Integer gender,
Department department) {
super();
this.id = id;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.department = department;
}
public Employee() {
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", department=" + department
+ "]";
}
}
b) Department
public class Department {
private Integer id;
private String departmentName;
public Department() {
}
public Department(int i, String string) {
this.id = i;
this.departmentName = string;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName;
}
@Override
public String toString() {
return "Department [id=" + id + ", departmentName=" + departmentName + "]";
}
}
2) Dao
a) EmployeeDao
import com.atguigu.springmvc.crud.entities.Department;
import com.atguigu.springmvc.crud.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> employees = null;
@Autowired
private DepartmentDao departmentDao;
static{
employees = new HashMap<Integer, Employee>();
employees.put(1001, new Employee(1001, "E-AA", "aa@163.com", 1, new Department(101, "D-AA")));
employees.put(1002, new Employee(1002, "E-BB", "bb@163.com", 1, new Department(102, "D-BB")));
employees.put(1003, new Employee(1003, "E-CC", "cc@163.com", 0, new Department(103, "D-CC")));
employees.put(1004, new Employee(1004, "E-DD", "dd@163.com", 0, new Department(104, "D-DD")));
employees.put(1005, new Employee(1005, "E-EE", "ee@163.com", 1, new Department(105, "D-EE")));
}
private static Integer initId = 1006;
public void save(Employee employee){
if(employee.getId() == null){
employee.setId(initId++);
}
employee.setDepartment(departmentDao.getDepartment(employee.getDepartment().getId()));
employees.put(employee.getId(), employee);
}
public Collection<Employee> getAll(){
return employees.values();
}
public Employee get(Integer id){
return employees.get(id);
}
public void delete(Integer id){
employees.remove(id);
}
}
b) DepartmentDao
import com.atguigu.springmvc.crud.entities.Department;
import org.springframework.stereotype.Repository;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
@Repository
public class DepartmentDao {
private static Map<Integer, Department> departments = null;
static{
departments = new HashMap<Integer, Department>();
departments.put(101, new Department(101, "D-AA"));
departments.put(102, new Department(102, "D-BB"));
departments.put(103, new Department(103, "D-CC"));
departments.put(104, new Department(104, "D-DD"));
departments.put(105, new Department(105, "D-EE"));
}
public Collection<Department> getDepartments(){
return departments.values();
}
public Department getDepartment(Integer id){
return departments.get(id);
}
}
2 功能实现
1 获取所有员工
在首页中创建超链接
<a href="${pageContext.request.contextPath}/getEmployees">获取所有员工</a>
创建处理器类EmployeeHandler
a) 注入EmployeeDao
b) 创建处理方法
import com.atguigu.springmvc.crud.dao.EmployeeDao;
import com.atguigu.springmvc.crud.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Collection;
import java.util.Map;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@RequestMapping(value = "getEmployees",method = RequestMethod.GET)
public String getEmployees(Map<String , Object> map){
//调用EmployeeDao中获取所有员工的方法
Collection<Employee> employees = employeeDao.getAll();
//将employees放到map中
map.put("emps",employees);
return "list";
}
}
在WEB-INF/views目录下创建视图页面list.jsp
a) 从request域中获取所有的员工
b) 使用jstl的if标签判断是否为空
i. 为空显示没有任何员工
ii. 非空使用forEach标签遍历所有员工
c) 使用EL表达式显示员工信息
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>查询所有员工</title>
</head>
<body>
<center>
<c:if test="${empty requestScope.emps}">
<h1>没有任何员工</h1>
</c:if>
<c:if test="${not empty requestScope.emps}">
<h1>员工信息</h1>
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>Id</th>
<th>LastName</th>
<th>Email</th>
<th>Gender</th>
<th>Department</th>
<th colspan="2">Operate</th>
</tr>
<c:forEach items="${requestScope.emps}" var="emp">
<tr>
<td>${emp.id}</td>
<td>${emp.lastName}</td>
<td>${emp.email}</td>
<td>
<c:if test="${emp.gender==1}">男</c:if>
<c:if test="${emp.gender==0}">女</c:if>
</td>
<td>${emp.department.departmentName}</td>
<td><a href="#">Edit</a></td>
<td><a href="#">Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</center>
</body>
</html>
2 添加员工
- 在list.jsp页面中创建添加员工的连接
<a href="${pageContext.request.contextPath}/addEmployee">添加新员工</a>
- 创建去添加员工页面的处理方法
a) 注入DepartmentDao获取所有部门信息
b) 向request域中添加一个没有任何属性值的Employee对象作为模型数据
@RequestMapping(value = "/addEmployee",method = RequestMethod.GET)
public String toAddEmployeePage(Map<String , Object> map){
//调用DepartmentDao中获取所有部门的方法
Collection<Department> departments = departmentDao.getDepartments();
//将departments放到map中
map.put("depts",departments);
//将一个没有任何属性值的Employee对象作为模型数据放到map中
map.put("emp",new Employee());
return "add";
}
- 创建添加员工的页面add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>添加员工的页面</title>
</head>
<body>
<h1>添加员工</h1>
<form:form modelAttribute="emp">
员工姓名:<form:input path="lastName"/><br>
员工邮箱:<form:input path="email"/><br>
员工性别:<form:radiobutton path="gender" value="1" label="男" />
<form:radiobutton path="gender" value="0" label="女" />
<br>
员工部门:<form:select path="department.id" items="${requestScope.depts}"
itemValue="id" itemLabel="departmentName"></form:select>
<br><br>
<input type="submit">
</form:form>
</body>
</html>
- 创建添加员工的处理方法
@RequestMapping(value = "/addEmployee",method = RequestMethod.POST)
public String addEmployee(Employee employee){
//调用EmployeeDao中添加员工的方法
employeeDao.save(employee);
//重定向到查询所有员工的URL
return "redirect:/getEmployees";
}
3 删除员工
- 在list.jsp页面的表单中设置删除员工的超链接
<td><a class="delEmp" id="${emp.lastName}" href="${pageContext.request.contextPath}/deleteEmployeeById/${emp.id}">Delete</a></td>
- 由于删除员工要发送Delete请求,但是Delete请求需要通过Post请求转换,而超链接发送的是Get请求,所以我们需要先将其转换为通过form表单发送Post请求,可以通过js代码转换。
<head>
<title>查询所有员工</title>
<script type="javascript" src="${pageContext.request.contextPath}/static/script/jquery-1.9.1.min.js"></script>
<script type="javascript">
$(function () {
//给删除员工的超链接绑定单击事件
$(".delEmp").click(function () {
//获取要删除的员工的名字
var lastName = $(this).attr("id");
//弹出提示框
var flag = confirm("确定要删除员工 "+lastName+" 吗?");
if(flag){
//获取超链接的href属性值
var url = $(this).attr("href");
//将url的值设置到form表单的action属性中
$("#deleteForm").attr("action",url);
//提交表单
$("#deleteForm").submit();
}
//取消默认行为,不让超链接发送请求
return false;
});
});
</script>
</head>
<body>
<form action="" method="post" id="deleteForm">
<input type="hidden" name="_method" value="delete">
</form>
- 创建处理方法
@RequestMapping(value = "/deleteEmployeeById/{id}",method = RequestMethod.DELETE)
public String deleteEmployeeById(@PathVariable("id") Integer id){
//调用EmployeeDao中删除员工的方法
employeeDao.delete(id);
//重定向到查询所有员工的URL
return "redirect:/getEmployees";
}
4 修改员工
- 在list.jsp页面的表单中设置编辑员工的超链接
<td><a href="${pageContext.request.contextPath}/updateEmployee/${emp.id}">Edit</a></td>
- 创建去修改员工页面的处理方法
@RequestMapping(value = "/updateEmployee/{id}",method = RequestMethod.GET)
public String toUpdateEmployeePage(@PathVariable("id") Integer id , Map<String , Object> map){
//调用EmployeeDao中获取员工信息的方法
Employee employee = employeeDao.get(id);
//调用DepartmentDao中获取所有部门的方法
Collection<Department> departments = departmentDao.getDepartments();
//将employee和departments放到map中
map.put("emp",employee);
map.put("depts",departments);
return "update";
}
- 创建修改员工的页面update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>更新员工的页面</title>
</head>
<body>
<h1>更新员工</h1>
<form:form modelAttribute="emp">
<input type="hidden" name="_method" value="put">
员工编号:<form:input path="id" readonly="true" /><br>
员工姓名:<form:input path="lastName"/><br>
员工邮箱:<form:input path="email"/><br>
员工性别:<form:radiobutton path="gender" value="1" label="男" />
<form:radiobutton path="gender" value="0" label="女" />
<br>
员工部门:<form:select path="department.id" items="${requestScope.depts}"
itemValue="id" itemLabel="departmentName"></form:select>
<br><br>
<input type="submit">
</form:form>
</body>
</html>
- 创建修改员工的处理方法
@RequestMapping(value = "/updateEmployee/{id}",method = RequestMethod.PUT)
public String updateEmployee(Employee employee){
//调用EmployeeDao中更新员工的方法
employeeDao.save(employee);
//重定向到查询所有员工的URL
return "redirect:/getEmployees";
}