补充先说明:
# ajax
1.如果没加 contentType: "application/json"
data就应该对应的是json对象 比如:{"name","zhangsan"} 或者 JSON.parse(dataString)
2.如果加了contentType:"application/json"
data就必须是字符串 比如: JSON.stringify(data);
# content-type
1. form-data、x-www-form-urlencoded
不可以用@RequestBody;可以用@RequestParam。这两种方式的时候没有json字符串部分。
2.application/json
json字符串部分可以用@RequestBody;url中的?后面参数可以用@RequestParam。
@PathVariable
@PathVariable:用于获取URL路径中的动态部分的值,通常处理RESTful风格的URL路径变量。例如:/api/users/{id} 中的 id
简单事例
@GetMapping("/api/users/{id}")
public String getUserById(@PathVariable int id) {
return "User ID: " + id;
}
@RequestParam
@RequestParam:接收的参数是来自HTTP请求体或请求url的QueryString中。他是用来处理 Content-Type 为 application/x-www-form-urlencoded 编码的时候的内容,可以采用 all 的请求方式,但是不支持 application/json,不推荐使用@RequestParam接收application/json,这时候就需要使用到@RequestBody。
# @RequestParam有三个配置参数
required 表示是否必须,默认为 true,必须
defaultValue 可设置请求参数的默认值
value 为接收url的参数名(相当于key值)
简单事例
# 代码
@GetMapping("/api/users")
public String getUserByName(@RequestParam String name) {
return "User: " + name;
}
@RequestBody
@RequestBody:处理[非,不支持] Content-Type: application/x-www-form-urlencoded编码格式的数据 支持比如:application/json 和 application/xml
# @RequestBody接收的参数是来自requestBody中,即请求体
GET请求中,因为没有HttpEntity,所以@RequestBody并不适用。
POST请求中,通过HttpEntity传递的参数,必须要在请求头中声明数据的类型Content-Type
SpringMVC通过使用 HandlerAdapter 配置的HttpMessageConverters来解析HttpEntity中的数据,然后绑定到相应的bean上。
简单事例
# 代码
@PostMapping("/api/users")
public String createUser(@RequestBody User user) {
return "User created: " + user.getName();
}
# 请求体(JSON)
{
"name": "John",
"age": 30
}
从注解方面总结:
| 注解 | 支持的类型 | 支持的请求类型 | 支持的 Content-Type | 请求示例 |
|---|---|---|---|---|
| @PathVariable | url | get | all | /path/{id} |
| @RequestParam | url | get | all | /path?id = |
| @RequestParam | body | post/put/delete/patch | form-data,x-www-form-urlencoded | |
| @RequestBody | body | post/put/delete/patch | json,非x-www-form-urlencoded |
更多内容欢迎关注 [ 小巫编程室 ] 公众号,喜欢文章的话,也希望能给小编点个赞或者转发,你们的喜欢与支持是小编最大的鼓励,小巫编程室感谢您的关注与支持。好好学习,天天向上(good good study day day up)。