1. 程式人生 > 其它 >SpringMVC知識盤點及總結4@RequestMapping註解的method屬性

SpringMVC知識盤點及總結4@RequestMapping註解的method屬性

學習目標@RequestMapping註解的method屬性

知識點三、

@RequestMapping註解的method屬性:

1. 匹配請求對映必須設定value,但是請求方式不是必須的

2.請求方式post和get來匹配請求對映,當同時設定了value和method屬性後,必須都滿足才
可以匹配請求對映。

3.get方式將請求引數用?拼接在瀏覽器url中發起請求,而post則將請求引數通過請求體發起請求。
兩種都是請求方式的格式都是name=value的形式。

4.get不安全但是響應快傳輸量小,post安全但是響應慢傳輸量大

5.測試:
(1)
success方法的註解裡,加上method屬性,以GET方式匹配請求對映

method ={RequestMethod.GET}

(2)在index.html中新增一個from表單裡面寫一個submit按鈕,設定提交方式為post
    <form th:action="@{/hello/test}" method="post">
         <input type="submit" value="測試RequestMapping的method屬性---->POST">
       </form>


(3)
啟動測試

點選測試按鈕,發現報405錯誤!Request method 'POST' not supported
設定匹配請求對映方式為GET,而以post發起請求,所以不能匹配請求對映。
同理post也一樣。

@RequestMapping註解的method屬性通過請求的請求方式(get或post)匹配請求對映
@RequestMapping註解的method屬性是一個RequestMethod型別的陣列,表示該請求對映能夠匹配多種請求方
式的請求
*若當前請求的請求地址滿足請求對映的value屬性,但是請求方式不滿足method屬性,則瀏覽器報錯405:

Request method 'POST' not supported

其中@RequestMapping有對於指定請求方式的控制器方法,@RequestMapping的派生註解:

GetMapping --- 處理get請求的對映
PostMapping --- 處理post請求的對映
PutMapping ---處理put請求的對映
DeleteMapping ---處理delete請求的對映


練習測試一下@GetMapping,此時就只需要寫value值
//測試指定對映請求的方式為GET
@GetMapping("testGetMapping")
            public String testGetMapping(){
                return  "success";
            }
<a th:href="@{/hello/testGetMapping}">測試GetMapping註解--->testGetMapping</a><br>

訪問成功


練習測試@PostMapping
       //測試指定對映請求的方式為POST
            @PostMapping("testPostMapping")
            public  String  testPostMapping(){
                return "success";
            }


     <form th:action="@{/hello/testPostMapping}" method="post">
            <input type="submit" value="測試PostMapping註解---post">
        </form>

練習測試@PutMapping
      //測試指定對映請求的方式為PUT
            @PutMapping(value = "/testPut")
            public  String testPut(){

                return "success";
            }


     <form th:action="@{/hello/testPut}" method="put">
            <input type="submit" value="測試form表單能否傳送put或者delete請求">
        </form>
           
以put請求報405錯! Request method 'GET' not supported
說明即使指定為put或者delete方式,也按照get進行請求


總結:目前瀏覽器只支援get和post,超連結是以get方式傳送請求,如果在from表單提交時,
為method設定了其他請求方式的字串(put或者delete),
則按照預設的請求get處理。