Spring MVC 框架:第七章:REST 架构风格 (1)
http://localhost:8080/shop/product/cellPhone/iPhone
第二节 SpringMVC 对四种请求方式的支持
1.说明
受 HTML 的限制,只有 GET 请求和 POST 请求是可以直接生成的。为了生成 PUT 和 DELETE 请求方式我们需要借助一个过滤器:org.springframework.web.filter.HiddenHttpMethodFilter,这个过滤器可以将 POST 请求转换为 PUT 或 DELETE 等其他形式。
2.HiddenHttpMethodFilter 的使用方法
①在 web.xml 中进行配置,拦截所有资源。
<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>
②在表单隐藏域中通过_method 请求参数附带请求方式名称
jsp 代码:
<input type="hidden" name="_method" value="put"/>
③通过点击超链接执行删除操作。
这是一个难点,超链接中没有表单隐藏域,所以需要将超链接转换为表单进行提交,这就需要借助于 JavaScript。
[1]在页面上创建一个 action 属性为空的 form 表单
jsp 代码:
<form method="POST">
<input type="hidden" name="_method" value="DELETE" />
</form>
[2]给所有超链接绑定单击响应函数
jsp 代码:
<a href="${pageContext.request.contextPath}/emp/ID" class="empRemove">删除</a>
jsp 中 jquery 代码:
$(".empRemove").click(function(){
//※※※※※※※※※以下操作将 GET 请求转换为 POST 请求※※※※※※※※※
//1.先获取到当前超链接原本要访问的 URL 地址
//this 是当前被点击的超链接的引用,是 DOM 对象
var targetUrl = this.href;
//2.获取负责转换请求方式的表单的 jQuery 对象
var ("form");
//3.将表单的 action 属性设置为超链接的 URL 地址
$form.attr("action",targetUrl );
//4.提交表单
//将表单元素封装为 jQuery 对象后调用 submit()方法可以提交表单,相当于点击表单的提交按钮
$form.submit();
//5.超链接不跳转
return false;
});
@PathVariable 注解
通过 URL 地址携带的数据需要通过 @PathVariable 注解来获取。它的用法是:
Handled 代码:
//使用 @PathVariable 注解将 URL 地址中的变量匹配出来
@RequestMapping(value="/emp/{empId}", method=RequestMethod.DELETE)
public String testPathVariable(@PathVariable("empId") String empId) {
System.out.println("empId="+empId);
return "redirect:/result";
}
实战代码:
项目结构
web.xml
<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:spring-mvc.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>
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</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>
spring-mvc.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.*" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
</bean>
mvc:annotation-driven</mvc:annotation-driven>
<mvc:default-servlet-handler />
</beans>
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>
<a href="${pageContext.request.contextPath }/emp">去 list 页面</a>
</body>
</html>
dataList.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>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
$(".remove").click(function(){
var data = $(this).parents("tr").children("td:eq(1)").text();
var confirm = window.confirm("你确定要"+data+"删除吗?");
if(!confirm){
return false;
}
//※※※※※※※※※以下操作将 GET 请求转换为 POST 请求※※※※※※※※※
//1.先获取到当前超链接原本要访问的 URL 地址
//this 是当前被点击的超链接的引用,是 DOM 对象
var targetUrl = this.href;
//2.获取负责转换请求方式的表单的 jQuery 对象
var ("form");
//3.将表单的 action 属性设置为超链接的 URL 地址
$form.attr("action",targetUrl );
//4.提交表单
//将表单元素封装为 jQuery 对象后调用 submit()方法可以提交表单,相当于点击表单的提交按钮
$form.submit();
//5.超链接不跳转
return false;
});
});
</script>
</head>
<body>
<form method="POST">
<input type="hidden" name="_method" value="DELETE" />
</form>
<center>
<table>
<c:if test="${empty requestScope.list }">
<tr>
<td>没有查询到数据</td>
</tr>
</c:if>
<c:if test="${!empty requestScope.list }">
<tr>
<td>ID</td>
<td>姓名</td>
<td>SSN</td>
<td>部门名称</td>
<td colspan="2">操作</td>
</tr>
<c:forEach items="${requestScope.list }" var="list">
<tr>
<td>${list.empId}</td>
<td>${list.empName}</td>
<td>${list.ssn }</td>
<td>${list.department.deptName }</td>
<td><a href="{list.empId}" class="remove">删除</a></td>
<td><a href="{list.empId}">编辑</a></td>
</tr>
</c:forEach>
</c:if>
<tr>
<td colspan="6" align="center">
<a href="${pageContext.request.contextPath }/emp/list">添加</a></td>
</tr>
</table>
</center>
</body>
</html>
dataEdit.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/emp"
method="post">
<input type="hidden" name="_method" value="put" />
<input type="hidden" name="empId" value="${requestScope.emdit.empId }"/>
<table>
<tr>
<td>姓名</td>
<td><input type="text" name="empName" value="${emdit.empName }" />
</td>
</tr>
<tr>
<td>SSN</td>
<td><input type="text" name="ssn" value="${emdit.ssn }" /></td>
</tr>
<tr>
<td>所在部门</td>
<td><select name="department.deptId">
<c:if test="${!empty deptList }">
<c:forEach items="${requestScope.deptList}" var="dept">
<c:if test="${dept.deptId==requestScope.emdit.department.deptId }">
<option value="{dept.deptName }</option>
</c:if>
<option value="{dept.deptName }</option>
</c:forEach>
</c:if>
</select></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="保存" /></td>
</tr>
</table>
</form>
</body>
</html>
dataAdd.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/emp" method="post">
<table>
<tr>
<td>姓名</td>
<td>
<input type="text" name="empName"/>
</td>
</tr>
<tr>
<td>SSN</td>
<td>
<input type="text" name="ssn"/>
</td>
</tr>
<tr>
<td>
所在部门</td>
<td>
<select name="department.deptId">
<c:if test="${empty deptList }">
<option>部门数据查询失败!!!</option>
</c:if>
<c:if test="${!empty deptList }">
<c:forEach items="${requestScope.deptList}" var="dept">
<option value="{dept.deptName }</option>
</c:forEach>
</c:if>
</select>
</td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="保存"/>
</td>
</tr>
</table>
</form>
</body>
</html>
DeptDao.java
package com.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Repository;
import com.pojo.Department;
@Repository
public class DeptDao {
private static Map<String, Department> dataMap;
private static Map<String, Department> namedMap;
static {
dataMap = new HashMap<>();
namedMap = new HashMap<>();
Department department = new Department(UUID.randomUUID().toString(), "市场部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "销售部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "行政部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "人事部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "技术部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
department = new Department(UUID.randomUUID().toString(), "公关部");
dataMap.put(department.getDeptId(), department);
namedMap.put(department.getDeptName(), department);
}
public static Department getDeptByName(String deptName) {
return namedMap.get(deptName);
}
public static Department getDeptById(String uuid) {
return dataMap.get(uuid);
}
public List<Department> getDeptList() {
return new ArrayList<>(dataMap.values());
}
}
EmpDao.java
package com.dao;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Repository;
import com.pojo.Department;
import com.pojo.Employee;
@Repository
public class EmpDao {
private static Map<String, Employee> dataMap;
static {
dataMap = new HashMap<>();
String empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "乔峰", "SSN001", DeptDao.getDeptByName("市场部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "虚竹", "SSN002", DeptDao.getDeptByName("市场部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "段誉", "SSN003", DeptDao.getDeptByName("市场部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "鸠摩智", "SSN004", DeptDao.getDeptByName("技术部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "萧远山", "SSN005", DeptDao.getDeptByName("技术部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "慕容复", "SSN006", DeptDao.getDeptByName("技术部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "段正淳", "SSN007", DeptDao.getDeptByName("公关部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "段延庆", "SSN008", DeptDao.getDeptByName("公关部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "丁春秋", "SSN009", DeptDao.getDeptByName("销售部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "无崖子", "SSN010", DeptDao.getDeptByName("人事部")));
empId = UUID.randomUUID().toString();
dataMap.put(empId, new Employee(empId, "慕容博", "SSN011", DeptDao.getDeptByName("人事部")));
}
public void saveEmp(Employee employee) {
String empId = UUID.randomUUID().toString();
employee.setEmpId(empId);
String deptId = employee.getDepartment().getDeptId();
Department department = DeptDao.getDeptById(deptId);
employee.setDepartment(department);
dataMap.put(empId, employee);
}
public void removeEmp(String empId) {
dataMap.remove(empId);
}
public void updateEmp(Employee employee) {
String deptId = employee.getDepartment().getDeptId();
Department department = DeptDao.getDeptById(deptId);
employee.setDepartment(department);
dataMap.put(employee.getEmpId(), employee);
}
public Employee getEmpById(String empId) {
return dataMap.get(empId);
}
public List<Employee> getEmpList() {
return new ArrayList<>(dataMap.values());
}
}
Department
package com.pojo;
public class Department {
private String deptId;
private String deptName;
public Department() {
}
public Department(String deptId, String deptName) {
super();
评论