在路由中定義變量規則后,通常我們需要在處理方法(也就是@RequestMapping注解的方法)中獲取這個URL變量的具體值,並根據這個值(例如用戶名)做相應的操作,Spring MVC提供的@PathVariable可以幫助我們:
@GetMapping("/users/{username}") public String userProfile(@PathVariable String username) { return String.format("user %s", username); }
在上述例子中,當@Controller處理HTTP請求時,userProfile的參數username會被自動設置為URL中的對應變量username(同名賦值)的值,例如當HTTP請求為:/users/tianmaying,URL變量username的值tianmaying會被賦給函數參數username,函數的返回值自然也就是:String.format("user %s", username);,即user tianmaying。
在默認情況下,Spring會對
@PathVariable注解的變量進行自動賦值,當然你也可以指定@PathVariable使用哪一個URL中的變量:@GetMapping("/users/{username}") public String userProfile(@PathVariable("username") String user) { return String.format("user %s", user); }這時,由於注解
String user的@PathVariable的參數值為username,所以仍然會將URL變量username的值賦給變量user
@RequestParam
@RequestParam和@PathVariable的區別就在於請求時當前參數是在url路由上還是在請求的body上,例如有下面一段代碼:
@RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestParam(value="phoneNum", required=true) String phoneNum ) String userName) { userService.create(phoneNum, userName); return "success"; }
這個接口的請求url這樣寫:http://xxxxx?phoneNum=xxxxxx,也就是說被@RequestParam修飾的參數最后通過key=value的形式放在http請求的Body傳過來,對比下上面的@PathVariable就很容易看出兩者的區別了。
@RequestBody直接以String接收前端傳過來的json數據
=================================
參考資料:
獲取URL變量
@RequestParam @RequestBody @PathVariable的作用
end
