学无先后,达者为师

网站首页 编程语言 正文

Required String paramter ‘username‘ is not present

作者:Pisces_224 更新时间: 2022-02-27 编程语言

原因

Spring Boot的注解@RequestParam不支持接受请求体内的json数据。

以下为转载他人部分:https://blog.csdn.net/qq_39506912/article/details/90107756
重点为对三个注解的比较


错误分析

使用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()
      	...
      
       

        原文链接:https://blog.csdn.net/qq_36256590/article/details/121822876

        栏目分类
        最近更新