@RequestMapping實現RESTful風格的增刪改查

1 Http協議定義的操作

Http協議定義了4這種操作方式(CRUD),分別爲GET,POST,PUT,DELETE
GET請求用於獲取資源
POST請求用於新建資源
PUT請求用於更新資源
DELETE請求用於刪除資源
但是超鏈接用於實現GET請求,表單用於實現POST請求,PUT和DELETE請求如何實現呢?

2 先看看原生javaWeb的執行流程

在這裏插入圖片描述
在請求時確定了請求方式是GET或者POST;然後請求經過過濾器過濾,最終才能被Servlet接受
所以對所有請求的統一處理過程可以利用過濾器類來實現。

SpringMVC實現了將POST請求轉爲PUT或者DELETE請求過程的類叫HiddenHttpMethodFilter

3 HiddenHttpMethodFilter的使用

向原生的javaWEB的filter一樣配置在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>

前端頁面

<a href="helloworld">GET</a>
    <br/><br/>
    <form action="helloworld" method="post">
        <input type="submit" value="POST">
    </form>
     <br/>
    <form action="helloworld" method="post">
        <input type="hidden" name="_method" value="PUT">
        <input type="submit" value="PUT">
    </form>
     <br/>
    <form action="helloworld" method="post">
        <input type="hidden" name="_method" value="DELETE">
        <input type="submit" value="DELETE">
    </form>

在這裏插入圖片描述
@RequestMapping代碼

@Controller
public class Distributor {
    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public String distribute2Success1() {
        System.out.println("GET");
        return "success";
    }
    @RequestMapping(value = "/helloworld", method = RequestMethod.POST)
    public String distribute2Success2() {
        System.out.println("POST");
        return "success";
    }
    @RequestMapping(value = "/helloworld", method = RequestMethod.PUT)
    public String distribute2Success3() {
        System.out.println("PUT");
        return "success";
    }
    @RequestMapping(value = "/helloworld", method = RequestMethod.DELETE)
    public String distribute2Success4() {
        System.out.println("DELETE");
        return "success";
    }
}

這時候點擊不同的連接,就會進入不同是我函數體,試想一下結合之前的@PathVariable註解。@RequestParam註解,就可以實現刪除,更新等操作,參照https://blog.csdn.net/qq_23937341/article/details/95970359
https://blog.csdn.net/qq_23937341/article/details/95999217

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章