@PathVariable @RequestParam @RequestBody 的作用

@PathVariable

當(dāng)使用@RequestMapping URI template 樣式映射時(shí),@PathVariable能使傳過來的參數(shù)綁定到路由上,這樣比較容易寫出restful api

demo1:單參? ? url :?http://127.0.0.1:8080/good/100

@RequestMapping("/test/{id}")

public int test(@PathVariable int id) {

? ? return id;

}

demo2:多參????url :?http://127.0.0.1:8080/test/10/100

@RequestMapping("/test/{type}/{id}")

public String test(@PathVariable long type, @PathVariable long id) {

? ? return type+","+id;

}

@RequestParam

接收的參數(shù)是來自HTTP請(qǐng)求體或請(qǐng)求url的QueryString中,使用該注解時(shí)Content-Type字段,需要為application/x-www-form-urlencoded,同時(shí),支持post和get

demo1:最簡單的,URL中的key與形參一致???url :?http://127.0.0.1:8080/test?id=100

@RequestMapping("/test")

public int test01(@RequestParam(required = true, defaultValue = "0") int id) {

? ? return id;

}

demo2:URL中的key與形參不一致????url :?http://127.0.0.1:8080/test?uid=100

@RequestMapping("/test")

public int test02(@RequestParam(value = "uid", defaultValue = "0") int id) {

? ? return id;

}

demo3:URL中一個(gè)key有多個(gè)值? ??url :?http://127.0.0.1:8080/test?id=100&id=200

@RequestMapping("/test")

public String test03(@RequestParam(value="id") long[] id){

? ? System.out.println(id);

? ? return "";

}

//或者是

@RequestMapping("/test")

public String test04(@RequestParam(value="list") List<Integer> list){

? ? System.out.println(list);

? ? return "";

}

demo4:一般使用map集合來接受多參? ??url :?http://127.0.0.1:8080/test?id=100&name=tom

@RequestMapping("/test")

public String test01(@RequestParam Map params){

????String name = params.get("name").toString();

????return name;

}

@RequestBody

該注解常用于接受請(qǐng)求體中非application/x-www-form-urlencoded編碼格式的數(shù)據(jù),比如:application/json、application/xml,現(xiàn)在前后端分離系統(tǒng)那么多,所以這才是主角。

總之

/{id}這種傳參形式可以用形式@PathVariable

url中的?后面參數(shù)可以用@RequestParam,?form-data、x-www-form-urlencoded可以用@RequestParam

application/json:json字符串可以用@RequestBody

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容