參數(shù)傳遞
參數(shù)傳遞可以說(shuō)是服務(wù)端和外界溝通的主要方式魄宏,這節(jié)是非常重要的!
本節(jié)內(nèi)容包括:
通過(guò)url傳參
|---get方式Url傳參
|---@PathVariable 即:url/id/1994 形式
|---@RequestParam 即:url?username=zed形式
|---POST方式傳參
|---@RequestParam
|---請(qǐng)求體中加入文本
配置文件傳參
<iframe src="http://player.bilibili.com/player.html?aid=39775932&cid=69872889&page=4" scrolling="no" border="0" width="1000px" height="700px" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>
1.get方式Url傳參:
@PathVariable
@RestController
public class HelloController {
@GetMapping("/hello/{name}")
public String hello(@PathVariable("name") String name){
// 形參的name可以隨意
System.out.println("獲取到的name是:"+name);
return "hello "+name;
}
}
- 訪問(wèn):http://localhost:8080/hello/lisi
2.get方式Url傳參:
@RequestParam
如果請(qǐng)求參數(shù)的名字跟方法中的形參名字一致可以省略@RequestParam("name")
@GetMapping("/hello")
public String hello(@RequestParam("name") String name){
System.out.println("獲取到的name是:"+name);
return "hello "+name;
}
3.get方式Url傳參:
@RequestParam+默認(rèn)參數(shù)
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",defaultValue = "admin") String name){
System.out.println("獲取到的name是:"+name);
return "hello "+name;
}
注意:如果沒(méi)有指定默認(rèn)值斤寇,并且沒(méi)有傳遞參數(shù)將會(huì)報(bào)錯(cuò)
Required String parameter 'name' is not present
:name參數(shù)沒(méi)有提供
- 解決方案
- 1.defaultValue = "xxx" :使用默認(rèn)值
- 2.required = false :標(biāo)注參數(shù)是非必須的
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",required = false) String name){
System.out.println("獲取到的name是:"+name);
return "hello "+name;
}
4.POST方式傳遞數(shù)據(jù)
@RestController
public class HelloController {
public static Logger log = LoggerFactory.getLogger(HelloController.class);
@PostMapping("/user")
public String add(@RequestParam("name") String name,@RequestParam("age") Integer age){
log.info(name+" "+age);
return "name:"+name+"\nage:"+age;
}
}
post不能用瀏覽器直接訪問(wèn)饭弓,這里用Postman測(cè)試:
5.POST傳遞字符串文本
通過(guò)HttpServletRequest獲取輸入流
@PostMapping("/PostString")
public String postString(HttpServletRequest request) {
ServletInputStream is = null;
try {
is = request.getInputStream();
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[1024];
int len = 0;
while ((len = is.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
System.out.println(sb.toString());
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
6.@requestbody接收參數(shù)
- @requestbody可以接收GET或POST請(qǐng)求中的參數(shù)
- 把json作為參數(shù)傳遞,要用【RequestBody】
- 附帶著說(shuō)一下使用postman方式設(shè)置content-type為application/json方式測(cè)試后臺(tái)接口
@PostMapping("/save")
@ResponseBody
public Map<String,Object> save(@RequestBody User user){
Map<String,Object> map = new HashMap<String,Object> ();
map.put("user",user);
return map;
}
@PostMapping("/user")
public String user(@RequestBody User user){
log.info(user.toString());
return null;
}
參考源碼下載: 點(diǎn)擊下載源碼