2022-04-04_sping boot处理请求
2022-04-03 本文已影响0人
微笑碧落
1.前端请求参数是一个对象
- 前端示例:
$.post("player/list",
{playerID:1},
(data)=>{players = data}
)
- sping boot书写方法
@RestController
@RequestMapping("record")
public class RecordController {
@PostMapping("new")
public String hello(Record record) {
System.out.println(Record.getPlayerID());
return "Hello World11!";
}
}
- 此时spring boot会自动把请求的对象传递给
hello方法 - 该方法可以带
@RequestParam注解,也可以不带。带了这个注解,表示参数不能有系统自动新建,不带这个参数,如果传递过来的json对象不正确,系统会自动新建一个。 - 前端传过来的对象必须和后端的bean对象属性一致
2.前端请求参数是一个JSON字符串
- 后端需要加(
@RequestBody注解,表示接受的一个JSON字符串 - 前端需要修改请求参数类型为JSON
- 后端接收数组参数的示例(推测post传递对象的话,只能传递单一对象,传递数组只能用这个JSON字符串)
- 注意
stringify方法 - sping boot书写方法
public String record(@RequestBody List<Record> records) {
System.out.println(records.get(0).getPlayerID());
return "Hello World11!";
}
- 前端的请求:
$.ajax({
url : "record/new",
type : "POST",
contentType:"application/json",
data:JSON.stringify([{},{}]),
success:function (data) {
alert("done")
}
}
)
3.get方式传递数组
前端请求:
http://localhost:8080/record/newg?js=1,2,3
//后端处理书写方式
@GetMapping("newg")
public String recordg(@RequestParam("js") List<Long> jss) {
System.out.println(jss.get(0));
return "Hello World11!";
}
4.告警代码Required request parameter 'js' for method parameter type List is not present
- 如果是get方式,表示请求没有这个参数
- 如果是post方式
5.告警代码Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
- 表示后端接收参数是用JSON字符串,但是前端传递的是JSON对象。需要对该JSON对象转换为JSON字符串
6.传递复杂嵌套对象的方法
- 复杂的对象,对象中嵌套对象的传递,一定要用如下方法,否则会报错
- 需要传递的对象:
{
obj1:{p1:,p2},
obj2:{}
}
- 前端发送方法
$.ajax({
url : "/projectRate/add",
type : "POST",
contentType:"application/json",
data:JSON.stringify(ceshi),
success:function (data) {
alert("done")
}
}
)
- 后端接收方法。注意(@RequestBody注解
public void add(@RequestBody ProjectRate projectRate){
System.out.println(projectRate);
}
参考文章
1.HTTP 方法:GET 对比 POST
2.SpringBoot 出现 Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported
3.springboot 不同请求方式下接收List 入参总结