REST CRUD案例
1.项目目录
2.导入上图中的所有jar包
3.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>RestEmp</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
4.配置springMVC.xml
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<context:component-scan base-package="com.atguigu.rest.crud"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"></property>
<property name="suffix" value=".jsp"></property>
<!-- <property name="order" value="1"></property> -->
</bean>
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
<property name="order" value="2"></property>
</bean> -->
<!-- 处理静态资源 -->
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
5.准备项目所需要的bean、dao
5.1 Employee.java
package com.atguigu.rest.crud.bean;
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;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email="
+ email + ", gender=" + gender + ", 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() {
// TODO Auto-generated constructor stub
}
}
5.2 Department.java
package com.atguigu.rest.crud.bean;
public class Department {
private Integer id;
private String departmentName;
public Department() {
// TODO Auto-generated constructor stub
}
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
+ "]";
}
}
5.3 EmployeeDao.java
package com.atguigu.rest.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.atguigu.rest.crud.bean.Department;
import com.atguigu.rest.crud.bean.Employee;
@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);
}
}
5.4 DepartmentDao.java
package com.atguigu.rest.crud.dao;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.atguigu.rest.crud.bean.Department;
@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);
}
}
6.准备项目需要的所有页面
6.1 list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<%-- <link rel="stylesheet" href="${pageContext.servletContext.contextPath}/css/index_like.css"> --%>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/css/index_work.css">
<script type="text/javascript" src="${pageContext.servletContext.contextPath}/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(function(){
$(".del").click(function(){
//submit()将所获得的form元素提交
if(confirm("确认删除吗?")){
$("form").attr("action", this.href).submit();//$(this).attr("href")
return false;//将超链接的默认行为取消
}
return false;//将超链接的默认行为取消
});
});//预加载函数或文档就绪函数
</script>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>LASTNAME</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>DEPARTMENTNAME</th>
<th>OPTION(<a href="emp">ADD</a>)</th>
</tr>
<c:forEach items="${emps}" var="emp">
<tr>
<td>${emp.id}</td>
<td>${emp.lastName}</td>
<td>${emp.email}</td>
<td>${emp.gender==0?'女':'男'}</td>
<td>${emp.department.departmentName}</td>
<td>
<a href="emp/${emp.id}">UPDATE</a>
<a class="del" href="emp/${emp.id}">DELETE</a>
</td>
</tr>
</c:forEach>
</table>
<form method="post">
<input type="hidden" name="_method" value="DELETE">
</form>
</body>
</html>
6.2 add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/css/index_work.css">
</head>
<body>
<form action="emp" method="post">
<table>
<tr>
<th colspan="2">添加员工信息</th>
</tr>
<tr>
<td>LASTNAME</td>
<td>
<input type="text" name="lastName">
</td>
</tr>
<tr>
<td>EMAIL</td>
<td>
<input type="text" name="email">
</td>
</tr>
<tr>
<td>GENDER</td>
<td>
<input type="radio" name="gender" value="1">男
<input type="radio" name="gender" value="0">女
</td>
</tr>
<tr>
<td>DEPARTMENT</td>
<td>
<select name="department.id">
<option>-SELECT DEPARTMENT-</option>
<c:forEach items="${depts}" var="dept">
<option value="${dept.id}">${dept.departmentName}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="ADD">
</td>
</tr>
</table>
</form>
</body>
</html>
6.3 update.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/css/index_work.css">
</head>
<body>
<form action="${pageContext.servletContext.contextPath}/emp" method="post">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="id" value="${emp.id}">
<table>
<tr>
<th colspan="2">修改员工信息</th>
</tr>
<tr>
<td>LASTNAME</td>
<td>
<input type="text" name="lastName" value="${emp.lastName}">
</td>
</tr>
<tr>
<td>EMAIL</td>
<td>
<input type="text" name="email" value="${emp.email}">
</td>
</tr>
<tr>
<td>GENDER</td>
<td>
<%-- <input type="radio" name="gender" value="1" <c:if test="${emp.gender==1}"> checked="checked"</c:if>>男
<input type="radio" name="gender" value="0" <c:if test="${emp.gender==0}"> checked="checked"</c:if>>女 --%>
<input type="radio" name="gender" value="1" ${emp.gender==1?'checked':''}>男
<input type="radio" name="gender" value="0" ${emp.gender==0?'checked':''}>女
</td>
</tr>
<tr>
<td>DEPARTMENT</td>
<td>
<select name="department.id">
<option>-SELECT DEPARTMENT-</option>
<c:forEach items="${depts}" var="dept">
<option value="${dept.id}" ${dept.id==emp.department.id?'selected':''}>${dept.departmentName}</option>
</c:forEach>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="UPDATE">
</td>
</tr>
</table>
</form>
</body>
</html>
6.4 edit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!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>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_work.css" />
</head>
<body>
<!-- 使用SpringMVC from标签重构添加/修改页面 -->
<!-- modelAttribute自定义回显对象的属性名 -->
<form:form action="${pageContext.servletContext.contextPath }/emp" method="post" modelAttribute="emp">
<c:if test="${empty emp.id}" var="flag"></c:if>
<c:if test="${!flag}">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT" />
</c:if>
<table>
<tr>
<th colspan="2">
<c:if test="${flag }">添加员工信息</c:if>
<c:if test="${!flag }">修改员工信息</c:if>
</th>
</tr>
<tr>
<td>LASTNAME</td>
<td>
<form:input path="lastName"/>
</td>
</tr>
<tr>
<td>EMAIL</td>
<td>
<form:input path="email"/>
</td>
</tr>
<tr>
<td>GENDER</td>
<td>
<form:radiobuttons path="gender" items="${genders}"/>
</td>
</tr>
<tr>
<td>DEPARTMENT</td>
<td>
<form:select path="department.id" items="${depts}" itemLabel="departmentName" itemValue="id"></form:select>
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${flag}">
<input type="submit" value="ADD" />
</c:if>
<c:if test="${!flag}">
<input type="submit" value="UPDATE" />
</c:if>
</td>
</tr>
</table>
</form:form>
</body>
</html>
7.EmpController_Old.java(实现添加修改的第一种方式,选择第二种方式时注释掉EmpController_Old类的@Controller注解)
package com.atguigu.rest.crud.controller;
import java.util.Collection;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.atguigu.rest.crud.bean.Department;
import com.atguigu.rest.crud.bean.Employee;
import com.atguigu.rest.crud.dao.DepartmentDao;
import com.atguigu.rest.crud.dao.EmployeeDao;
//@Controller
public class EmpController_Old {
//添加修改的第一种方式
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
/**
* 获取所有的员工信息
*/
@RequestMapping(value="/emps")
public String getAll(Map<String, Object> map){
Collection<Employee> emps = employeeDao.getAll();
map.put("emps", emps);
return "list";
}
/**
* 跳转到添加页面
*/
@RequestMapping(value="/emp", method=RequestMethod.GET)
public String toAdd(Map<String, Object> map){
Collection<Department> depts = departmentDao.getDepartments();
map.put("depts", depts);
return "add";
}
/**
* 添加员工信息
*/
@RequestMapping(value="/emp", method=RequestMethod.POST)
public String addEmp(Employee employee){
employeeDao.save(employee);
return "redirect:/emps";
}
/**
* 获取要回显的数据,跳转到修改页面,并回显
*/
@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
public String toUpdate(@PathVariable("id")Integer id, Map<String, Object> map){
//获取要修改的员工信息
Employee emp = employeeDao.get(id);
//所有的部门信息,供用户选择
Collection<Department> depts = departmentDao.getDepartments();
map.put("emp", emp);
map.put("depts", depts);
return "update";
}
@RequestMapping(value="/emp", method=RequestMethod.PUT)
public String updateEmp(Employee employee){
employeeDao.save(employee);//修改
return "redirect:/emps";
}
}
8.EmpController.java(实现添加修改的第二种方式,选择第一种方式时注释掉EmpController类的@Controller注解)
package com.atguigu.rest.crud.controller;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.atguigu.rest.crud.bean.Department;
import com.atguigu.rest.crud.bean.Employee;
import com.atguigu.rest.crud.dao.DepartmentDao;
import com.atguigu.rest.crud.dao.EmployeeDao;
@Controller
public class EmpController {
//添加修改的第二种方式
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
/**
* 获取所有的员工信息
* @param map
* @return
*/
@RequestMapping(value="/emps")
public String getAll(Map<String, Object> map) {
Collection<Employee> emps = employeeDao.getAll();
map.put("emps", emps);
return "list";
}
/**
* 跳转到添加页面
* @return
*/
@RequestMapping(value="/emp", method=RequestMethod.GET)
public String toAdd(Map<String, Object> map) {
//获取所有的部门信息
Collection<Department> depts = departmentDao.getDepartments();
//创建存储性别gender的信息
Map<String, String> genders = new HashMap<>();
genders.put("0", "女");
genders.put("1", "男");
map.put("depts", depts);
map.put("genders", genders);
//form标签有自动回显的功能,会在页面中能够默认获取request作用于中command属性的值
//map.put("command", new Employee());
//若在<form:form>设置了modelAttribute,就可以自定义回显对象的属性名
map.put("emp", new Employee());
return "edit";
}
/**
* 添加员工信息
* @param employee
* @return
*/
@RequestMapping(value="/emp", method=RequestMethod.POST)
public String addEmp(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}
/**
* 获取要回显的数据,跳转到修改页面,并回显
* @param id
* @param map
* @return
*/
@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
public String toUpdate(@PathVariable("id") Integer id, Map<String, Object> map) {
//获取要修改的员工信息
Employee emp = employeeDao.get(id);
//所有的部门信息,供用户选择
Collection<Department> depts = departmentDao.getDepartments();
//设置存储性别的map集合
Map<String, String> genders = new HashMap<>();
genders.put("0", "女");
genders.put("1", "男");
map.put("emp", emp);
map.put("depts", depts);
map.put("genders", genders);
return "edit";
}
/**
* 修改员工信息
*/
@RequestMapping(value="/emp", method=RequestMethod.PUT)
public String updateEmp(Employee employee) {
employeeDao.save(employee);//修改
return "redirect:/emps";
}
@RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
public String deleteEmp(@PathVariable("id")Integer id){
employeeDao.delete(id);
return "redirect:/emps";
}
}