springMVC筆記系列(7)——HiddenHttpMethodFilter過濾器

什麼是REST?首先來段介紹吧。html

REST: 即 Representational State Transfer。 (資源)表現層狀態轉化。 是目前最流行的一種互聯網軟件架構。它結構清晰、符合標準、易於理解、 擴展方便,因此正獲得愈來愈多網站的採用。java

資源(Resources) : 網絡上的一個實體,或者說是網絡上的一個具體信息。它能夠是一段文本、一張圖片、一首歌曲、一種服務, 總之就是一個具體的存在。能夠用一個URI(統一資源定位符)指向它, 每種資源對應一個特定的 URI 。 要獲取這個資源, 訪問它的URI就能夠, 所以 URI 即爲每個資源的獨一無二的識別符。web

表現層(Representation) : 把資源具體呈現出來的形式,叫作它的表現層(Representation) 。好比,文本能夠用 txt 格式表現,也能夠用 HTML 格式、 XML 格式、 JSON 格式表現,甚至能夠採用二進制格式。spring

狀態轉化(State Transfer) : 每發出一個請求, 就表明了客戶 端和服務器的一次交互過程。 HTTP協議,是一個無狀態協議,即全部的狀態都保存在服務器端。所以, 若是客戶端想要操做服務器,必須經過某種手段, 讓服務器端發生「shell

狀態轉化」(State Transfer)。而這種轉化是創建在表現層之上的,因此就是 「表現層狀態轉化」。 具體說, 就是 HTTP 協議裏面,四個表示操做方式的動詞: GET、 POST、 PUT、 DELETE。它們分別對應四種基本操做: GET 用來獲取資源, POST 用來新建資源, PUT 用來更新資源, DELETE 用來刪除資源。(本文出自:http://my.oschina.net/happyBKs/blog/416994)apache

示例:瀏覽器

– /order/1    HTTP  GET : 獲得 id =  1 的 order   spring-mvc

– /order/1    HTTP  DELETE: 刪除 id = 1 的 order   tomcat

– /order/1    HTTP  PUT:更新id = 1 的 order   服務器

– /order      HTTP  POST:新增 order

可是要用spring實現四個方法須要一個過濾器:

HiddenHttpMethodFilter: 瀏覽器 form 表單只支持 GET與 POST 請求,而DELETE、 PUT 等 method 並不支持, Spring3.0 添加了一個過濾器,能夠將這些請求轉換爲標準的 http 方法,使得支持 GET、 POST、 PUT 與DELETE 請求。

帶佔位符的 URL 是 Spring3.0 新增的功能, 該功能在SpringMVC 向 REST 目 標挺進發展過程當中具備里程碑的意義。

經過 @PathVariable 能夠將 URL 中佔位符參數綁定到控制器處理方法的入參中: URL 中的 {xxx} 佔位符能夠經過@PathVariable("xxx") 綁定到操做方法的入參中。


好吧,話很少說,咱們實際操練一下,在webapp目錄下的原web.xml中添加HiddenHttpMethodFilter過濾器

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  
  
  <!-- 配置 org.springframework.web.filter.HiddenHttpMethodFilter,能夠吧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>
  
  
  
  
  <!--  配置DispatcherServlet -->
  <!-- 下面的代碼爲STS自動生成,若是是通常的eclipse須要安裝springIDE插件 -->
  <!-- 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>
		<!-- 配置DispatcherServlet的一個初始化參數:配置springmvc 配置位置和名稱 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value><!-- classpath下的springmvc.xml -->
		</init-param>
		<!-- load-on-startup是指這個servlet是在當前web應用被加載的時候就被建立,而不是第一次被請求的時候被建立 -->
		<load-on-startup>1</load-on-startup>
	</servlet>

<!-- 	Map all requests to the DispatcherServlet for handling
	/表明能夠應答全部請求,由springDispatcherServlet處理 -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

springMVC.xml與以前的文章中的例子相比,沒有變化,這裏爲了讀者方便也一塊兒給出,關於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"
	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.1.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

<!-- 配置自動掃描的包 -->
<context:component-scan base-package="com.happyBKs.springmvc.handlers"></context:component-scan>

<!-- 配置視圖解析器:如何把handler方法 的返回值 解析爲 實際的物理視圖-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>


</beans>

接下來寫控制器類及其方法,來負責接收和處理請求:RestTestHandler類

package com.happyBKs.springmvc.handlers;

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;

@RequestMapping("/rest")
@Controller
public class RestTestHandler {
	
	/*
	 * Rest 風格的Url        原先利用請求參數的風格
	 * 以CRUD爲例
	 * 新增: /order POST		
	 * 修改:/order/1 Put 		update?id=1
	 * 獲取:/order/1 GET 		get?id=1
	 * 刪除:/order/1 DELETE		delete?id=1
	 * 
	 * 如何發送PUT請求和DELETE請求?
	 * 1.須要配置HiddenHttpMethodFilter
	 * 2.須要發送POST請求
	 * 3.須要在發送POST請求時攜帶一個name=」_method「的隱藏域,值爲DELETE或PUT
	 *	
	 * 在SpringMVC的目標方法中如何獲得id呢?
	 * 使用@PathVariable註解
	 */
	
	
	@RequestMapping(value="/methodstest/{id}",method=RequestMethod.GET)
	public String restGet(@PathVariable int id)//當@PathVariable沒有標明{id},
	{
		System.out.println("get "+id);
		System.out.println("querry operations...");
		return "querry";
	}
	
	@RequestMapping(value="/methodstest",method=RequestMethod.POST)
	public String restPost()
	{
		System.out.println("post ");
		System.out.println("post operations...");
		return "post";
	}
	
	@RequestMapping(value="/methodstest/{id}",method=RequestMethod.PUT)
	public String restPut(@PathVariable int id)
	{
		System.out.println("put "+id);
		System.out.println("put operations...");
		return "put";
	}
	
	@RequestMapping(value="/methodstest/{id}",method=RequestMethod.DELETE)
	public String restDelete(@PathVariable int id)
	{
		System.out.println("delete "+id);
		System.out.println("delete operations...");
		return "delete";
	}
}

請求頁面編寫以下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<a href="rest/methodstest/1">GET Request</a>

	<form action="rest/methodstest" method="post">
		<input type="submit" value="POST Request" />
	</form>

	<form action="rest/methodstest/1" method="post">
		<input type="hidden" name="_method" value="PUT">
		<input type="submit" value="PUT Request" />
	</form>

	<form action="rest/methodstest/1" method="post">
		<input type="hidden" name="_method" value="DELETE">
		<input type="submit" value="DELETE Request" />
	</form>
</body>
</html>

注意到了嗎?HiddenHttpMethodFilter幫助咱們實現對put請求和delete請求的模擬。它會將帶有隱藏域_method的POST請求轉換爲put請求和delete請求提交給服務器。

過程:

點擊四個連接和表單按鈕:

控制檯輸入爲:

get 1
querry operations...
post 
post operations...
put 1
put operations...
delete 1
delete operations...

總結:

 Rest 風格的Url        原先利用請求參數的風格

* 以CRUD爲例

* 新增: /order POST

* 修改:/order/1 Put update?id=1

* 獲取:/order/1 GET get?id=1

* 刪除:/order/1 DELETEdelete?id=1


* 如何發送PUT請求和DELETE請求?

 1.須要配置HiddenHttpMethodFilter

 2.須要發送POST請求

 3.須要在發送POST請求時攜帶一個name=」_method「的隱藏域,值爲DELETE或PUT

* 在SpringMVC的目標方法中如何獲得id呢?

 使用@PathVariable註解


——————————————————————————————

注意:我用的是Tomcat7服務器。tomcat8彷佛不支持PUT和DELETE請求,即便我已經在Tomcat的conf文件夾下的web.xml加入了readonly參數並設置爲false,依然不能解決問題。

    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
		
		<init-param> 
			<param-name>readonly</param-name> 
			<param-value>false</param-value> 
		</init-param> 
		
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

點擊post請求和delete請求的結果是:

相關文章
相關標籤/搜索