SpringBoot中接收POST參數(shù)的幾種方式詳解
SpringBoot中接收POST參數(shù)的幾種方式
今天在做一個vue前后端分離項目的過程中,踩了一個坑,記錄一下
前端如下:

用戶名字段:username
密碼字段:password
提交后,發(fā)現(xiàn)后端怎么也收不到參數(shù),總結(jié)如下:
常見的接收post參數(shù),有三種
1、接收表單數(shù)據(jù)
@RestController
public class xxx {
@PostMapping("/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password){
System.out.println("用戶名:" + username + ", 密碼: " + password);
return "用戶名:" + username + ", 密碼: " + password;
}
}額外參數(shù):
- 使用 required = false 標(biāo)注參數(shù)是非必須的。
- 使用 defaultValue 給參數(shù)指定個默認(rèn)值。
2、接收map數(shù)據(jù)
map結(jié)構(gòu)數(shù)據(jù)接收方式:
@RestController
public class xxx {
@PostMapping("/login")
public String login(@RequestParam Map<String, Object> map){
System.out.println("用戶名:" + map.get("username") + ", 密碼: " + map.get("password") );
return "用戶名:" + map.get("username") + ", 密碼: " + map.get("password");
}
}3、接收數(shù)組或List接收多個參數(shù)
@RestController
public class xxx {
@PostMapping("/login")
public String login(@RequestParam String[] n){
return Arrays.toString(n);;
}
}4、接收json數(shù)據(jù)參數(shù)

明顯看出,是json結(jié)構(gòu)的,是我大意了,沒有閃~~
注意:使用的是 @RequestBody
@RestController
public class xxx {
@PostMapping("/login")
public String login(@RequestBody Map<String, Object> map){
System.out.println("用戶名:" + map.get("username") + ", 密碼: " + map.get("password") );
return "用戶名:" + map.get("username") + ", 密碼: " + map.get("password");
}
}Springboot接收GET和POST請求參數(shù)
接收GET請求參數(shù):
@RestController
public class test {
//參數(shù)可以為空
@GetMapping("/test")
public String hello(@RequestParam(name = "name", required = false) String name) {
return "獲取到的name是:" + name;
}
}沒有參數(shù)時為null


Controller 還可以直接使用 map 來接收所有的請求參數(shù):
@RestController
public class HelloController {
@GetMapping("/test")
public String hello(@RequestParam Map<String, Object> params) {
return "name:" + params.get("name") + "<br>age:" + params.get("age");
}
}
使用map接收post請求參數(shù):params.get()當(dāng)中的參數(shù)就是表單的name值
@RestController
public class HelloController {
@PostMapping("/hello")
public String hello(@RequestParam Map<String,Object> params) {
return "name:" + params.get("name") + "\nage:" + params.get("age");
}
}<form action="http://localhost:8080/hello" method="post"> <input type="text" name="name" value="" /> <input type="text" name="age" value="" /> <input type="submit" value="提交"/> </form>

到此這篇關(guān)于SpringBoot中接收POST參數(shù)的幾種方式的文章就介紹到這了,更多相關(guān)SpringBoot接收POST參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring MVC+FastJson+hibernate-validator整合的完整實例教程
這篇文章主要給大家介紹了關(guān)于Spring MVC+FastJson+hibernate-validator整合的完整實例教程,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04
Spring監(jiān)聽器及定時任務(wù)實現(xiàn)方法詳解
這篇文章主要介紹了Spring監(jiān)聽器及定時任務(wù)實現(xiàn)方法詳解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07

