SpringBoot中Required String parameter '×××' is not present解决方法

错误分析

使用Post向接口发送json数据时显示如下错误:

WARN 13392 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved exception caused by handler execution: org.springframework.web.bind.MissingServletRequestParameterException: 
Required String parameter 'userName' is not present

查看json数据并无格式问题,查阅资料发现是接口接受传参问题,我这里使用了@RequestParam注解来接受数据,而这个注解不支持接受请求体内的json数据。

@PostMapping("/account")
public Object insertAccount(@RequestParam("userName") String userName) {
	...

解决方法

下面是对@PathVariable@RequestParam@RequestBody三者的比较

注解 支持的类型 支持的请求类型 支持的Content-Type 请求示例
@PathVariable url GET 所有 /test/{id}
@RequestParam url GET 所有 /test?id=1
Body POST/PUT/DELETE/PATCH form-data或x-www.form-urlencoded id:1
@RequestBody Body POST/PUT/DELETE/PATCH json {"id":1}

将接口改成以@RequestBody注解方式接受json请求数据,而后将接收到的json数据转化为json对象,可以使用json对象的get()方法取得参数值,代码如下:

@PostMapping("/account")
public Object insertAccount(@RequestBody JSONObject jsonParam) {
	String userName=jsonParam.get("userName").toString()
	...

你可能感兴趣的:(SpringBoot)