Get
最简单的get
@GetMapping("/get1")
public String get1() {
return "hello world";
}
传参数的get
@GetMapping("/get2")
public String get2(String world) {
return "hello" + world;
}
// @RequestParam
@GetMapping("/get3")
public String get3(@RequestParam String world) {
return "hello" + world;
}
通过postman测试,如果传参数world,两种方法返回的结果是一样的。
如果不传参数,
第一种方法,world会默认为null;
第二种方法,@RequestParam会报错
"error": "Bad Request", "message": "Required String parameter 'world' is not present",
看@RequestParam源码会看到如下,
boolean required() default true;
说明默认是一个必填的,也就是可以 改成选填的。
@GetMapping("/get4")
public String get4(@RequestParam(required = false) String world) {
return "hello" + world;
}
改一下,真的可以哎,不传参数,默认就是null了。
如果默认想显示个别的文字怎么办?
再看一眼源码(配置方式类似于required属性)
String defaultValue() default ValueConstants.DEFAULT_NONE;
Post
先来看一下postman
简单的介绍一下
form-data --> multipart/form-data 可以上传键值对或者文件
x-www-form-urlencoded --> application/x-www-form-urlencoded 键值对,此处的键值对不是{key1:value1,key2:value2}这种感觉,而是key1=value1&key2=value2
raw --> 任意格式的文本text,json,xml,html
post
@PostMapping("post1")
public String post1(String name, String address) {
return helloStr + name + "_" + address;
}
@PostMapping("post2")
public String post2(Student student) {
return helloStr + student.getName() + "_" + student.getAddress();
}
上面的两种写法,都可以通过form-data x-www-form-urlencoded进行请求。
使用json的时候,后台返回null
post json
@PostMapping("post3")
public String post3(@RequestBody Student student) {
return helloStr + student.getName() + "_" + student.getAddress();
}
@RequestBody
简单的总结一下,@RequestBody的时候,只能捕获到application/json类型的数据。
Axios
主要讲一下get和post
get
axios.get('/user?ID=12345')
axios.get('/user', {
params: {
ID: 12345
}
})
注意第二种用对象的形式,前面有一个神奇的 params
post
分别使用axios对java端的post1,post2,post3进行请求。发现,只有post3能够返回值。
然后观察请求详情,axios post请求默认发送的是application/json
看了下axios的源码,默认的Content-Type是application/x-www-form-urlencoded
对于请求的数据,里面有一个判断。
var DEFAULT_CONTENT_TYPE = {
'Content-Type': 'application/x-www-form-urlencoded'
};
if (utils.isObject(data)) {
setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
return JSON.stringify(data);
}
如果是Object,此处判断将头部改为application/json;charset=utf-8
axios本质上是对XMLHttpRequest的封装。
所以post请求请求的数据类型跟XMLHttpRequest就是一样的。
FormData
object对象经过axios内部转化(JSON.stringify(obj))这种情况就对应了spring boot中的@RequestBody
object对象通过querystring手动转化为key1=value1&key2=value2
欢迎讨论。有不足请指出。