RESTful风格CRUD操作的具体实现代码下载地址:http://download.youkuaiyun.com/download/bingbeichen/9795651。
1. 具体需求
2. 代码结构
3. 具体实现
DepartmentDao.java:
package com.qiaobc.springmvc.dao;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.qiaobc.springmvc.domain.Department;
@Repository
public class DepartmentDao {
private static Map<Integer, Department> depts = null;
static {
depts = new LinkedHashMap<Integer, Department>();
depts.put(101, new Department(101, "dept-101"));
depts.put(102, new Department(102, "dept-102"));
depts.put(103, new Department(103, "dept-103"));
}
public Collection<Department> getDepartments(){
return depts.values();
}
public Department getDepartment(Integer deptId) {
return depts.get(deptId);
}
}
EmployeeDao.java:
package com.qiaobc.springmvc.dao;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.qiaobc.springmvc.domain.Department;
import com.qiaobc.springmvc.domain.Employee;
@Repository
public class EmployeeDao {
private static Map<Integer, Employee> emps = null;
static {
emps = new LinkedHashMap<Integer, Employee>();
emps.put(1001, new Employee(1001, "qiaobc1001", "qiaobc1001@163.com", "1", new Department(101, "dept-101")));
emps.put(1002, new Employee(1002, "qiaobc1002", "qiaobc1002@163.com", "0", new Department(102, "dept-102")));
emps.put(1003, new Employee(1003, "qiaobc1003", "qiaobc1003@163.com", "1", new Department(103, "dept-103")));
emps.put(1004, new Employee(1004, "qiaobc1004", "qiaobc1004@163.com", "0", new Department(102, "dept-102")));
emps.put(1005, new Employee(1005, "qiaobc1005", "qiaobc1005@163.com", "1", new Department(101, "dept-101")));
}
public Collection<Employee> getEmployees() {
return emps.values();
}
private static Integer initId = 1006;
@Autowired
private DepartmentDao departmentDao;
public void save(Employee employee) {
if(employee.getId() == null) {
employee.setId(initId++);
}
employee.setDept(departmentDao.getDepartment(employee.getDept().getDeptId()));
emps.put(employee.getId(), employee);
}
public void delete(Integer id) {
emps.remove(id);
}
public Employee get(Integer id) {
return emps.get(id);
}
}
Department.java:
package com.qiaobc.springmvc.domain;
public class Department {
private Integer deptId;
private String deptName;
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Department(Integer deptId, String deptName) {
super();
this.deptId = deptId;
this.deptName = deptName;
}
public Department() {
super();
}
@Override
public String toString() {
return "Department [deptId=" + deptId + ", deptName=" + deptName + "]";
}
}
Employee.java:
package com.qiaobc.springmvc.domain;
public class Employee {
private Integer id;
private String name;
private String email;
private String gender;
private Department dept;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
public Employee(Integer id, String name, String email, String gender,
Department dept) {
super();
this.id = id;
this.name = name;
this.email = email;
this.gender = gender;
this.dept = dept;
}
public Employee() {
super();
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", email=" + email
+ ", gender=" + gender + ", dept=" + dept + "]";
}
}
EmployeeHandler.java:
package com.qiaobc.springmvc.handler;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.qiaobc.springmvc.dao.DepartmentDao;
import com.qiaobc.springmvc.dao.EmployeeDao;
import com.qiaobc.springmvc.domain.Employee;
@Controller
public class EmployeeHandler {
@Autowired
private EmployeeDao employeeDao;
@Autowired
private DepartmentDao departmentDao;
@RequestMapping(value="/emps", method=RequestMethod.GET)
public String list(Map<String, Object> map) {
map.put("employees", employeeDao.getEmployees());
return "emp-list";
}
@RequestMapping(value="/emp", method=RequestMethod.GET)
public String input(Map<String, Object> map) {
map.put("employee", new Employee());
map.put("departments", departmentDao.getDepartments());
return "emp-edit";
}
@RequestMapping(value="/emp", method=RequestMethod.POST)
public String save(Employee employee) {
System.out.println(employee);
employeeDao.save(employee);
return "redirect:/emps";
}
@RequestMapping(value="/emp/{id}", method=RequestMethod.DELETE)
public String delete(@PathVariable("id") Integer id) {
employeeDao.delete(id);
return "redirect:/emps";
}
@RequestMapping(value="/emp/{id}", method=RequestMethod.GET)
public String input(Map<String, Object> map, @PathVariable(value="id") Integer id) {
map.put("employee", employeeDao.get(id));
map.put("departments", departmentDao.getDepartments());
return "emp-edit";
}
@ModelAttribute
public void getEmployee(@RequestParam(value="id", required=false) Integer id, Map<String, Object> map) {
if(id != null) {
map.put("employee", employeeDao.get(id));
}
}
@RequestMapping(value="/emp", method=RequestMethod.PUT)
public String update(Employee employee) {
System.out.println(employee);
employeeDao.save(employee);
return "redirect:/emps";
}
}
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">
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置自动扫描的包 -->
<context:component-scan base-package="com.qiaobc.springmvc"></context:component-scan>
<mvc:default-servlet-handler/>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
emp-edit.jsp:
<%@page import="java.util.HashMap"%>
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
<!--
SpringMVC的form标签可以更快速地开发表单页面,并实现表单的回显
注意:
可以通过modelAttribute属性指定所绑定的模型属性
若未指定该属性,则默认从request域对象中获取名为command的表单Bean对象,若不存在则报错!
-->
<form:form action="${pageContext.request.contextPath }/emp" method="post" modelAttribute="employee">
<!-- path属性对应HTML表单标签的name属性值 -->
<c:if test="${!empty id }">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT">
Name:<form:input path="name" disabled="true"/>
</c:if>
<c:if test="${empty id }">
Name:<form:input path="name"/>
</c:if>
<br><br>
Email:<form:input path="email"/><br><br>
<%
Map<String, String> genders = new HashMap<String, String>();
genders.put("1", "Male");
genders.put("0", "Female");
request.setAttribute("genders", genders);
%>
Gender:<form:radiobuttons path="gender" items="${genders }"/><br><br>
Department:<form:select path="dept.deptId" items="${departments }"
itemLabel="deptName" itemValue="deptId" ></form:select><br><br>
<input type="submit" name="submit">
</form:form>
</body>
</html>
emp-list.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<!--
关于SpringMVC处理静态资源的问题:
1). DispatcherServlet的请求映射配置为“/”,即SpringMVC将捕获WEB容器的所有请求
2). 静态资源的请求如scripts/jquery-1.7.2.js会被捕获,会因找不到对应处理器将导致错误
3). 而优雅的REST风格的资源URL不希望带.do等后缀,即不能使用“/*.do”
解决办法:
1). 在SpringMVC配置文件中,配置<mvc:default-servlet-handler/>
2). 且需要配置<mvc:annotation-driven></mvc:annotation-driven>
-->
<script type="text/javascript" src="scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var href = $(this).attr("href");
$("form").attr("action", href).submit();
return false;
});
});
</script>
<body>
<form action="" method="post">
<input type="hidden" name="_method" value="DELETE">
</form>
<c:if test="${empty requestScope.employees }">
对不起,暂没有员工信息!
</c:if>
<c:if test="${!empty requestScope.employees }">
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>NAME</th>
<th>EMAIL</th>
<th>GENDER</th>
<th>DEPARTMENT</th>
<th>DELETE</th>
<th>EDIT</th>
</tr>
<c:forEach items="${requestScope.employees }" var="emp">
<tr>
<td>${emp.id }</td>
<td>${emp.name }</td>
<td>${emp.email }</td>
<td>${emp.gender == "1" ? "Female" : "Male" }</td>
<td>${emp.dept.deptName }</td>
<td><a href="emp/${emp.id }" class="delete">Delete</a></td>
<td><a href="emp/${emp.id }">Edit</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
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">
<!-- 配置SpringMVC所需要的DispatcherServlet -->
<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>
<!-- 配置可以拦截的请求对象 -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 配置HiddenHttpMethodFilter:将POST请求转换为DELETE或PUT请求 -->
<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>
index.jsp:
<%@ 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>Insert title here</title>
</head>
<body>
<!-- 显示所有员工信息的请求:HTTP GET -->
<a href="emps">List All Employees!</a>
<br><br>
<!-- 添加新的员工信息的请求:HTTP GET -->
<a href="emp">Add New Employee!</a>
<br><br>
</body>
</html>
本文介绍了一个基于Spring MVC的RESTful风格CRUD操作实例,详细展示了Department和Employee两个实体类的增删改查功能实现过程。
737

被折叠的 条评论
为什么被折叠?



