SpringBoot中Required String parameter `xxx` 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请求示例
@PathVariableurlGET所有/test/{id}
@RequestParamurlGET所有/test?id=1
BodyPOST/PUT/DELETE/PATCHform-data或x-www.form-urlencodedid:1
@RequestBodyBodyPOST/PUT/DELETE/PATCHjson{"id":1}

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

@PostMapping("/account")
public Object insertAccount(@RequestBody JSONObject jsonParam) {
	String userName=jsonParam.get("userName").toString()
	...
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值