SpringMVC ------HiddenHttpMethodFilter 過濾器

    Spring3.0之後添加了HiddenHttpMethodFilter過濾器,來支持支持Rest 風格的URL請求。
html

    REST  url:
java

          —  /order/1  HTTP GET  :獲得 id = 1 的order
web

          —  /order/1  HTTP DELETE  :刪除 id = 1 的orderajax

          —  /order/1  HTTP PUT  :更新 id = 1 的orderspring

          —  /order/1  HTTP POST :新增 id = 1 的orderapp

    首先配置到web.xml文件中post

<!-- 能夠報POST轉成DELETE請求 或POST 請求 -->
<filter>
    <filter-name>HiddenHttperMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>

<filter-mapping>
    <filger-name>HiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

  在POST的 請求中設置參數 _method="DELETE" url

<form action="/test/order/1" method="post">
    <input type="hidden" name="_method" value="DELETE" />
    <input type="submit" value="test delete" />
</form>

<form action="/test/order/1" method="post">
    <input type="hidden" name="_method" value="PUT" />
    <input type="submit" value="test PUT" />
</form>

    編寫Java方法spa

@RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
public String testRest(@PathVariable Integer id){
    System.out.println("test delete:"+id);
    return "success";
}

@RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
public String testRest(@PathVariable Integer id){
    System.out.println("test delete:"+id);
    return "success";
}

    原來,在HiddenHttpMethodFilter中的doFilterInternal ,會先去POST請求中獲取_method這個參數,根據參數的名字來轉發請求。code

    注意:若是你使用ajax進行傳輸數據,那麼你也應該按照上面的方式作。在你傳輸數據data裏面包含:_method:"PUT"的鍵值對,而且傳輸方式依舊設置爲"POST".

    否則,你用ajax用"PUT"的方式請求,SpringMVC將沒法找到你所要傳輸的數據,throw Handler execution resulted in exception: Request method 'POST' not supported 這樣的異常信息。

    看源代碼能夠知道,在SpingMVC中本質上只識別GET,POST!

相關文章
相關標籤/搜索