1. 程式人生 > >Spring REST(4)

Spring REST(4)

總結 pack XML 技術 method type con too request

REST風格

  /user/1 get請求   獲取用戶

  /user/1  post請求  新增用戶

  /user/1  put請求  更新用戶

  /user/1  delete請求  刪除用戶

在Spring MVC中如何提交put和delete請求呢?

  需要在web.xml文件中配置一個HiddenHttpMethodFilter過濾器。該過濾過濾post請求,如果在post請求中有個一個_method參數,那麽_method參數值就是請求方式。所以在jsp頁面可以這樣寫

技術分享圖片
 1 <a href="user/1">GET請求</a>
 2 
 3 <form action="user/1" method="post">
 4     <input type="submit" value="POST請求"/>
 5 </form>
 6 
 7 <form action="user/1" method="post">
 8     <input type="hidden" name="_method" value="PUT">
 9     <input type="submit" value="PUT請求"/>
10 </form>
11 
12 <form action="user/1" method="post">
13     <input type="hidden" name="_method" value="DELETE">
14     <input type="submit" value="DELET請求"/>
15 </form> 
技術分享圖片

  web.xml配置過濾器

技術分享圖片
1 <filter>
2     <filter-name>methodFilter</filter-name>
3     <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
4 </filter>
5 
6 <filter-mapping>
7     <filter-name>methodFilter</filter-name>
8     <url-pattern>/*</url-pattern>
9 </filter-mapping>
技術分享圖片

  控制器

技術分享圖片
 1 package com.proc;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.PathVariable;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RequestMethod;
 7 
 8 @Controller
 9 public class User {
10 
11     @RequestMapping(value="user/{id}",method=RequestMethod.GET)
12     public String get(@PathVariable("id") Integer id){
13         System.out.println("獲取用戶:"+id);
14         return "hello";
15     }
16     
17     @RequestMapping(value="user/{id}",method=RequestMethod.POST)
18     public String post(@PathVariable("id") Integer id){
19         System.out.println("添加用戶:"+id);
20         return "hello";
21     }
22     
23     @RequestMapping(value="user/{id}",method=RequestMethod.PUT)
24     public String put(@PathVariable("id") Integer id){
25         System.out.println("更新用戶:"+id);
26         return "hello";
27     }
28     
29     @RequestMapping(value="user/{id}",method=RequestMethod.DELETE)
30     public String delete(@PathVariable("id") Integer id){
31         System.out.println("刪除用戶:"+id);
32         return "hello";
33     }
34 }
技術分享圖片

  我們一次點擊GET請求、POST請求、PUT請求和DELETE請求

獲取用戶:1
添加用戶:1
更新用戶:1
刪除用戶:1

【總結】:發出PUT請求和DELET請求的步驟

  1、在發出請求時必須是POST請求

  2、在POST請求中添加一個名為_method的參數,其值用來指定是PUT請求還是DELETE請求

  3、配置HiddenHttpMethodFilter過濾器。該過濾器的作用是POST請求可以轉換成PUT或DELET請求

Spring REST(4)