1.獲取參數的集中常見注解
- @PathVariable:一般我們使用URI template樣式映射使用,即url/{param}這種形式,也就是一般我們使用的GET,DELETE,PUT方法會使用到的,我們可以獲取URL后所跟的參數。
- @RequestParam:一般我們使用該注解來獲取多個參數,在()內寫入需要獲取參數的參數名即可,一般在PUT,POST中比較常用。
- @RequestBody:該注解和@RequestParam殊途同歸,我們使用該注解將所有參數轉換,在代碼部分在一個個取出來,也是目前我使用到最多的注解來獲取參數
2.獲取請求路徑參數
- get請求,url路徑傳參
get請求一般通過url傳參,如:
http://localhost:8080/piano/add?brand="xinde" & price = "1200"
后端要獲取這些參數,可以使用@RequestParam注解
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam Integer id){
return "id:"+id;
}
- get請求,url路徑參數
后端可以使用@PathVariable接收路徑參數
@RestController
public class HelloController {
@RequestMapping(value="/piano/{brand}/{price}",method= RequestMethod.GET)
public String sayHello(@PathVariable("price") Integer id,@PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}