一丶@RequestParam
@RequestParam接收的参数是来自requestHeader中,即请求头。通常用于GET请求。
@RequestParam有三个配置参数:
- required 表示是否必须,默认为 true,必须。
- defaultValue 可设置请求参数的默认值。
- value为接收url的参数名(相当于key值)。
@RequestParam用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的内容,Content-Type默认为该属性。
eg:
前台请求:
url=http://localhost:8080/edit?name=zhang&age=23
后台接收:
@RequestMapping("/edit")
public String edit(
@RequestParam(value=“name”) String name,
@RequestParam(value=“age”) Long age) {
…
}
二丶@RequestBody
@RequestBody接收的参数是来自requestBody中,即请求体。
一般用于处理非Content-Type: application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml等类型的数据。
@RequestBody可以将body里面所有的json数据传到后端,后端再进行解析。
前端使用$.ajax请求,一定要指定 contentType: “application/json;charset=utf-8;”,默认为 application/x-www-form-urlencoded。
eg:
后台接收:
@RequestMapping("/edit")
public String edit(@RequestBody List entity) {
…
}
三丶@PathVariable
@PathVariable接收参数,参数值需要在url进行占位。
前端传参的URL于后端@RequestMapping的URL必须相同且参数位置一一对应,否则前端会找不到后端地址。
eg:
前台请求:
url=http://localhost:8080/edit/${name}/${age}
后台接收:
@RequestMapping("/edit/{name}/{age}")
public String edit(
@PathVariable String name,
@PathVariable Long age) {
…
}