示例:
/order/1 HTTP GET :得到 id = 1 的 order
/order/1 HTTP DELETE:删除 id = 1的 order
/order/1 HTTP PUT:更新id = 1的 order
/order HTTP POST:新增 order
HiddenHttpMethodFilter:浏覽器 form 表單隻支援 GET 與 POST 請求,而DELETE、PUT 等 method 并不支
持,Spring3.0 添加了一個過濾器,可以将這些請求轉換為标準的 http 方法,使得支援 GET、POST、PUT 與DELETE 請求。
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">
<!--
配置 org.springframework.web.filter.HiddenHttpMethodFilter: 可以把 POST 請求轉為 DELETE 或 POST 請求
-->
<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>
<!-- 配置 DispatcherServlet -->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置 DispatcherServlet 的一個初始化參數: 配置 SpringMVC 配置檔案的位置和名稱 -->
<!--
實際上也可以不通過 contextConfigLocation 來配置 SpringMVC 的配置檔案, 而使用預設的.
預設的配置檔案為: /WEB-INF/<servlet-name>-servlet.xml
-->
<!--
<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>
</web-app>
controller
/ * 如何發送 PUT 請求和 DELETE 請求呢 ?
* 1. 需要配置 HiddenHttpMethodFilter
* 2. 需要發送 POST 請求
* 3. 需要在發送 POST 請求時攜帶一個 name="_method" 的隐藏域, 值為 DELETE 或 PUT
*
* 在 SpringMVC 的目标方法中如何得到 id 呢? 使用 @PathVariable 注解
*
*/
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)//更新
public String testRestPut(@PathVariable Integer id) {
System.out.println("testRest Put: " + id);
return SUCCESS;
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)//删除
public String testRestDelete(@PathVariable Integer id) {
System.out.println("testRest Delete: " + id);
return SUCCESS;
}
@RequestMapping(value = "/testRest", method = RequestMethod.POST)//新增
public String testRest() {
System.out.println("testRest POST");
return SUCCESS;
}
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)//查詢
public String testRest(@PathVariable Integer id) {
System.out.println("testRest GET: " + id);
return SUCCESS;
}
jsp
<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="PUT"/>
<input type="submit" value="TestRest PUT"/>
</form>
<br><br>
<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="TestRest DELETE"/>
</form>
<br><br>
<form action="springmvc/testRest" method="post">
<input type="submit" value="TestRest POST"/>
</form>
<br><br>
<a href="springmvc/testRest/1" target="_blank" rel="external nofollow" >Test Rest Get</a>
<br><br>
例子
1. 顯示所有員工資訊
– URI:emps
– 請求方式:GET
2. 添加員工
– 顯示添加頁面:
• URI:emp
• 請求方式:GET
– 添加員工資訊:
• URI:emp
• 請求方式:POST
• 顯示效果:完成添加,重定向到 list 頁面
3. 删除操作
– URL:emp/{id}
– 請求方式:DELETE
– 删除後效果:對應記錄從資料表中删除
4.– 顯示修改頁面:
• URI:emp/{id}
• 請求方式:GET
• 顯示效果:回顯表單。
– 修改員工資訊:
• URI:emp
• 請求方式:PUT
• 顯示效果:完成修改,重定向到 list 頁面。
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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>springmvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置 SpringMVC 的 DispatcherServlet -->
<!-- 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>
<!-- 配置 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>
jsp
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>
<!--
scripts/jquery-1.9.1.min.js"不能加載
SpringMVC 處理靜态資源:
1. 為什麼會有這樣的問題:
優雅的 REST 風格的資源URL 不希望帶 .html 或 .do 等字尾
若将 DispatcherServlet 請求映射配置為 /,
則 Spring MVC 将捕獲 WEB 容器的所有請求, 包括靜态資源的請求, SpringMVC 會将他們當成一個普通請求處理,
因找不到對應處理器将導緻錯誤。
2. 解決: 在 SpringMVC 的配置檔案中配置 <mvc:default-servlet-handler/>
-->
<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(function(){
$(".delete").click(function(){
var href =$(this).attr("href");
$("#del").attr("action",href).submit();
return false;//讓a标簽不起連結作用
});
});
</script>
</head>
<body>
<form action="" method="POST" id="del">
<input type="hidden" name="_method" value="DELETE">
</form>
<c:if test="${empty requestScope.employees }">
沒有任何員工資訊
</c:if>
<c:if test="${!empty requestScope.employees }">
<table cellpadding="10" cellspacing="0">
<tr>
<th>ID</th>
<th>LastName</th>
<th>Email</th>
<th>Gender</th>
<th>Department</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<c:forEach items="${requestScope.employees}" var="emp">
<tr>
<td>${emp.id }</td>
<td>${emp.lastName }</td>
<td>${emp.email }</td>
<td>${emp.gender ==0?'Female':'Male' }</td>
<td>${emp.department.departmentName }</td>
<td><a href="emp/${emp.id }" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >Edit</a></td>
<td><a class="delete" href="emp/${emp.id }" target="_blank" rel="external nofollow" target="_blank" rel="external nofollow" >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
<!-- -->
<br><br>
<a href="emp" target="_blank" rel="external nofollow" >添加新員工</a>
</body>
</html>
input.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>
<!--
1. WHY 使用 form 标簽呢 ?
可以更快速的開發出表單頁面, 而且可以更友善的進行表單值的回顯
2. 注意:
可以通過 modelAttribute 屬性指定綁定的模型屬性,
若沒有指定該屬性,則預設從 request 域對象中讀取 command 的表單 bean
如果該屬性值也不存在,則會發生錯誤。
-->
<form:form action="${pageContext.request.contextPath }/emp"
method="POST" modelAttribute="empolyee">
<c:if test="${empolyee.id ==null }">
<!-- path屬性對應html 表單标簽的name屬性 -->
LastName:<form:input path="lastName" />
</c:if>
<c:if test="${empolyee.id !=null }">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT">
</c:if>
<br>
Email:<form:input path="email" />
<br>
<%
Map<String, String> genders = new HashMap();
genders.put("1", "Male");
genders.put("0", "Female");
request.setAttribute("genders", genders);
%>
Gender:<form:radiobuttons path="gender" items="${genders}"
delimiter="<br>" />
<br>
Department:<form:select path="department.id" items="${departments}"
itemLabel="departmentName" itemValue="id"></form:select>
<br>
<br>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
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/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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- 配置自定掃描的包 -->
<context:component-scan base-package="com.me.springmvc"></context:component-scan>
<!-- 配置視圖解析器: 如何把 handler 方法傳回值解析為實際的實體視圖 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--
default-servlet-handler 将在 SpringMVC 上下文中定義一個 DefaultServletHttpRequestHandler,
它會對進入 DispatcherServlet 的請求進行篩查, 如果發現是沒有經過映射的請求, 就将該請求交由 WEB 應用伺服器預設的
Servlet 處理. 如果不是靜态資源的請求,才由 DispatcherServlet 繼續處理
一般 WEB 應用伺服器預設的 Servlet 的名稱都是 default.
若所使用的 WEB 伺服器的預設 Servlet 名稱不是 default,則需要通過 default-servlet-name 屬性顯式指定
使用該配置需要配置<mvc:annotation-driven/> 否則RequestMapping不起作用
-->
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
controller
package com.me.springmvc.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.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.me.springmvc.dao.DepartmentDao;
import com.me.springmvc.dao.EmployeeDao;
import com.me.springmvc.entities.Employee;
@Controller
public class EmployeeControllr {
@Autowired
EmployeeDao employeeDao;
@Autowired
DepartmentDao departmentDao;
/**
* @ModelAttribute注解執行@RequestMapping的請求時,會先執行該方法,
* 該方法作用:送出的修改表單沒有lastName,通過此方法保證更新操作的時候,lastName不為空,還是原來的值
* @param id
* @param map
*/
@ModelAttribute
public void getEmployee(@RequestParam(value = "id", required = false) Integer id, Map<String, Object> map) {
if (id != null) {
map.put("employee", employeeDao.get(id));
}
}
/**
* 修改的時候 送出的表單沒有lastName,通過 getEmployee方法來補全lastName的值,否則修改後lastName為null
* @param employee
* @return
*/
@RequestMapping(value = "/emp", method = RequestMethod.PUT)
public String update(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}
/**
* 轉到修改頁面,進行表單回顯
* @param id
* @param map
* @return
*/
@RequestMapping(value = "/emp/{id}", method = RequestMethod.GET)
public String input(@PathVariable("id") Integer id, Map<String, Object> map) {
map.put("empolyee", employeeDao.get(id));
map.put("departments", departmentDao.getDepartments());
return "input";
}
/*
* 轉到添加頁面
*/
@RequestMapping(value = "/emp", method = RequestMethod.GET)
public String input(Map<String, Object> map) {
map.put("departments", departmentDao.getDepartments());
// 解決
// java.lang.IllegalStateException: Neither BindingResult nor plain
// target object for bean name 'command' available as request attribute
// 往map添加 empolyee鍵值對 頁面表單添加 modelAttribute="empolyee"
// <form:form action="emp" method="POST" modelAttribute="empolyee">
// 預設是modelAttribute="command"
map.put("empolyee", new Employee());
return "input";
}
@RequestMapping(value = "/emp", method = RequestMethod.POST)
public String save(Employee employee) {
employeeDao.save(employee);
return "redirect:/emps";
}
@RequestMapping(value = "/emp/{id}", method = RequestMethod.DELETE)
public String delete(@PathVariable Integer id) {
employeeDao.delete(id);
return "redirect:/emps";
}
@RequestMapping("/emps")
public String list(Map<String, Object> map) {
Collection<Employee> employees = employeeDao.getAll();
map.put("employees", employees);
return "list";
}
}
springmvc 有時候離奇的不能進通路controller可能是編譯環境和tomcat運作環境不一緻!
http://pan.baidu.com/s/1c1GSKEG