org.springframework.web.bind.MissingServletRequestParameterException

发布时间:2022-06-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了org.springframework.web.bind.MissingServletRequestParameterException脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

问题发生

对接口进行测试时。

情况介绍/分析

已实现一个接口:

package com.ybqdren.controller.center;

import com.ybqdren.pojo.Users;
import com.ybqdren.service.center.CenterUserService;
import com.ybqdren.utils.IMOOCJSONResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Wen(Joan) Zhao <withzhaowen@126.com>
 * 2021/11/9
 */

@Api(value = "center - 用户中心",tags = {"用户中心展示的相关接口"})
@RestController
@RequestMapping("center")
public class CenterController {
    @Autowired
    private CenterUserService centerUserService;

    @ApiOperation(value = "获取用户信息",notes = "获取用户信息",httpMethod = "GET")
    @GetMapping("userinfo")
    public IMOOCJSONResult userinfo(
            @ApiParam(name = "userId",value="用户id",required = true)
            @RequestParam String userid
    ){
        Users user = centerUserService.queryUserInfo(userid);
        return IMOOCJSONResult.ok(user);
    }
}

此处我们使用请求参数注解RequestParam,用来获取:

http://localhost:8080/center/userinfo/userid=xxx

这种形式的请求参数。

由于此处我们没有在RequestParam注解中指定参数的名称,所以SpringBoot会默认去url寻找一个叫userid的参数。

问题解决

问题定位

根据错误中的:

MissingServletRequestParameterException

可知是参数传递的问题。

再看:

Required request parameter 'userid' for method parameter type String is not present]

会发现,一个叫做userid的参数出现了问题。

检查前端传入的参数名称:

serverUrl + '/center/userInfo?userId=' + userInfo.id, 

回顾情况介绍/分析中,我们并没有指定RequestParam注解接受的参数名称,所以其在url中寻找的是一个叫做userid的参数,故而没找到。

解决方案

因此我们可以用下面三种方式进行解决:

  1. 修改前端传入过来的参数名称(学习环境可以用,但是最不推荐使用)
  2. 修改当前路由方法参数名称
  3. 在RequestParam注解中设置name的值(最好的一种方法)

脚本宝典总结

以上是脚本宝典为你收集整理的org.springframework.web.bind.MissingServletRequestParameterException全部内容,希望文章能够帮你解决org.springframework.web.bind.MissingServletRequestParameterException所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: