SpringBoot優(yōu)雅接收前端請求參數(shù)的詳細(xì)過程
@RequestParm
我們可以通過
@RequestParm注解去綁定請求中的參數(shù),將(查詢參數(shù)或者form表單數(shù)據(jù))綁定到controller的方法參數(shù)中,通俗點說就是,我們可以在get請求和post請求中使用改注解,get請求中會從查詢參數(shù)中獲取參數(shù),post請求會從form表單或者查詢參數(shù)中獲取參數(shù)
- 默認(rèn)情況下,方法參數(shù)上使用該注解說明這個參數(shù)是必傳的,但是我們可以通過
required = false來設(shè)置是否必傳,或者通過defaultValue設(shè)置默認(rèn)值。 - 如果類型不是Sting類型的話,會自動進行轉(zhuǎn)換
- 可以將參數(shù)類型聲明為list,同一個參數(shù)名解析多個參數(shù)值
1.使用Get請求
/**
*GET http://localhost:8080/api/person/getPerson?id=1
*/
@GetMapping("/getPerson")
public String getPerson(@RequestParam(value = "id",required = false,defaultValue = "2") Integer id) {
log.info("id:{}", id);
return "";
}2.使用Post請求
/**
* POST http://localhost:8080/api/person/postPerson
* Content-Type: application/x-www-form-urlencoded
*
* id=1
*/
@PostMapping("/postPerson")
public String postPerson(@RequestParam("id") String id) {
log.info("id:{}", id);
return "";
}3.使用Map接收
/**
*POST http://localhost:8080/api/person/postPersonMap
* Content-Type: application/x-www-form-urlencoded
*
* id=1
*/
@PostMapping("/postPersonMap")
public String postPersonMap(@RequestParam HashMap<String,String> param) {
log.info("param:{}",param.toString());
return "";
}4.使用List接收
/**
*可以通過兩種方式傳遞list
* 第一種傳遞到param中:
* POST http://localhost:8080/api/person/postPersonList?param=1,2,3,4
*
* 第二種傳遞到form表單中:
* POST http://localhost:8080/api/person/postPersonList
* Content-Type: application/x-www-form-urlencoded
*
* param=1,2,3,4,5
*/
@PostMapping("/postPersonList")
public String postPersonList(@RequestParam List<String> param) {
log.info("param:{}",param);
return "";
}5.什么都不加
? 如果不加的話,前端可以不傳id。默認(rèn):get請求通過param傳遞,post請求通過form表單傳遞
/**
* GET http://localhost:8080/api/person/getPerson?id=1
*/
@GetMapping("/getPersonById")
public String getPersonById(Integer id) {
log.info("id:{}", id);
return "";
}@RequestBody
@RequestBody主要用來接收前端傳遞給后端的json字符串中的數(shù)據(jù)的(請求體中的數(shù)據(jù)的);
如果參數(shù)未傳的話,引用類型默認(rèn)是null,基本類型為默認(rèn)值
注:一個請求,只有一個RequestBody;一個請求,可以有多個RequestParam。
### test postPersonByJson
POST http://localhost:8080/api/person/postPersonByJson
Content-Type: application/json
{
"id": 1,
"name": "tom",
"age": 12,
"ADDRESS": "beijing"
}默認(rèn)json的key和屬性名稱必須要匹配的,并且大小寫敏感
如果有別名的話可以使用@JsonAlias注解或者使用@JsonProperty注解如下:
/**
* 地址
*/
@JsonAlias(value = {"ADDRESS"})
private String adress; /**
* 地址
*/
@JsonProperty("ADDRESS")
private String adress;服務(wù)端接收如下:
@PostMapping("/postPersonByJson")
public Person postPersonByJson(@RequestBody Person person) {
log.info("person:{}", person);
return person;
}HttpEntity
HttpEntity 和@RequestBody使用相同,多了一個header
### test httpEntity
POST http://localhost:8080/api/person/accounts
Content-Type: application/json
{
"id": 1,
"name": "tom",
"age": 12,
"ADDRESS": "beijing"
} /**
* HttpEntity 和@RequestBody使用相同,多了一個header
*
* @param entity
*/
@PostMapping("/accounts")
public void handle(HttpEntity<Person> entity) {
log.info("請求頭部為:{},請求體為:{}", entity.getHeaders(), entity.getBody());
}@RequestHeader
@RequestHeader 主要用于接收前端header中的參數(shù),可以獲取指定的header屬性,也可以通過Map統(tǒng)一接收請求頭中的參數(shù)
### test header GET http://localhost:8080/api/person/getPersonHeader Accept-Encoding: deflate Keep-Alive: 11 ### test headerByMap GET http://localhost:8080/api/person/getPersonHeaderByMap Accept-Encoding: deflate Keep-Alive: 11
/**
* 接收header參數(shù)
*/
@GetMapping("/getPersonHeader")
public void getPersonHeader(@RequestHeader("Accept-Encoding") String encoding,
@RequestHeader("Keep-Alive") long keepAlive) {
log.info("Accept-Encoding:{},Keep-Alive:{}", encoding, keepAlive);
}
/**
* map接收header參數(shù)
* 使用map接收key值會變成小寫
*/
@GetMapping("/getPersonHeaderByMap")
public void getPersonHeader(@RequestHeader Map<String, String> param) {
param.forEach((key, value) -> {
log.info("key:{},value:{}", key, value);
});
log.info("Accept-Encoding:{},Keep-Alive:{}", param.get("accept-encoding"), param.get("keep-alive"));
}@PathVariable
使用@PathVariable注解可以獲取url中的參數(shù),也可以使用正則表達式提取url中的多個變量
### test PathVariable GET http://localhost:8080/api/person/1 ### test PathVariable regular expression GET http://localhost:8080/api/person/express/spring-web-3.0.5.jar
/**
* 獲取url中的參數(shù)
*/
@GetMapping("/{id}")
public void getPersonById(@PathVariable String id) {
log.info("id:{}", id);
}
/**
* 通過正則表達式獲取url中name,version,ext等信息
*/
@GetMapping("/express/{name:[a-z-]+}-{version:\\d\\.\\d\\.\\d}{ext:\\.[a-z]+}")
public void handle(@PathVariable String name, @PathVariable String version, @PathVariable String ext) {
log.info("name:{},version:{},ext:{}", name, version, ext);
}@ModelAttribute
@ModelAttribute可以作用在方法上和方法參數(shù)上,
標(biāo)記在方法的參數(shù)上,會將客戶端傳遞過來的參數(shù)按名稱注入到指定對象中
標(biāo)記在方法上,會在每一個@RequestMapping標(biāo)注的方法前執(zhí)行。
###test modelAttribute POST http://localhost:8080/api/person/postPersonByModel/123 Content-Type: application/x-www-form-urlencoded name=tom&age=14&address=北京 ###test getModelAttribute GET http://localhost:8080/api/person/getPersonByModel/456?name=tom&age=14&address=北京
@PostMapping("/postPersonByModel/{id}")
public void postPersonByModel(@ModelAttribute Person person) {
log.info("person:{}", person);
}
@GetMapping("/getPersonByModel/{id}")
public void getPersonByModel(@ModelAttribute Person person) {
log.info("person:{}", person);
}或者將@ModelAttribute注解放到方法上,如果有公共參數(shù)需要進行處理,可以使用@ModelAttribute進行前置操作例如:
### testModelAttribute POST http://localhost:8080/api/person/testModelAttribute Content-Type: application/x-www-form-urlencoded token: 123 name=tom&age=14&address=北京
@ModelAttribute
public void userInfo(ModelMap modelMap, HttpServletRequest request) {
log.info("執(zhí)行modelAttribute方法");
//模擬通過token獲取userId的過程
String id = request.getHeader("token").toString();
modelMap.addAttribute("userId", id);
}
@PostMapping("/testModelAttribute")
public void testModelAttribute(@ModelAttribute("userId") String userId, Person person) {
log.info("userId:{}", userId);
}到此這篇關(guān)于SpringBoot如何優(yōu)雅接收前端請求參數(shù)的文章就介紹到這了,更多相關(guān)SpringBoot接收前端請求參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java并發(fā)編程中的CyclicBarrier使用解析
這篇文章主要介紹了Java并發(fā)編程中的CyclicBarrier使用解析,CyclicBarrier從字面意思上來看,循環(huán)柵欄,這篇文章就來分析下是到底是如何實現(xiàn)循環(huán)和柵欄的,需要的朋友可以參考下2023-12-12
Springboot通用mapper和mybatis-generator代碼示例
這篇文章主要介紹了Springboot通用mapper和mybatis-generator代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-12-12
一文讀懂a(chǎn)va中的Volatile關(guān)鍵字使用
volatile關(guān)鍵字的作用保證了變量的可見性(visibility)。被volatile關(guān)鍵字修飾的變量,如果值發(fā)生了變更,其他線程立馬可見,避免出現(xiàn)臟讀的現(xiàn)象。這篇文章主要介紹了ava中的Volatile關(guān)鍵字使用,需要的朋友可以參考下2020-03-03

