昨天系统有个绑定手机号的功能接口,绑定提交一直报错不好使,报错如下:

GlobalExceptionHandler.exceptionHandler:message:Required request parameter 'token' for method parameter type String is not present, stackTrace:
[org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValueInternal(RequestParamMethodArgumentResolver.java:218), 
org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValue(RequestParamMethodArgumentResolver.java:193), 
org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:114), 
org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121), 
org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179), 
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146), 
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117), 
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895),
......

        这个报错很明显是参数传递时出现问题,看接口代码:

    @RequestMapping(value = "/binding", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<?, ?> bindingMobile(@RequestBody UserVo userInfo, @RequestParam(value = "token") String token) {
    // 内容省略
}

我看这个参数写法,一阵头大,POST请求,获取参数怎么还用 @RequestParam 注解,这匹配不了啊。我这边查看了请求,发现token参数是在请求头中,于是修改了接口参数:

    @RequestMapping(value = "/binding", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<?, ?> bindingMobile(@RequestBody UserVo userInfo, HttpServletRequest request) {
       
        // 获取token
        String token = request.getHeader("token");
        
        // 下面内容省略
}

上面修改后参数获取就没问题了,接口功能也好使了。

网上有个博主列出了请求类型和参数的对应表,我觉得挺好的,引用一下:

注解支持的类型支持的请求类型支持的Content-Type请求示例
@PathVariableurlGET所有/test/{id}
@RequestParamurlGET所有/test?id=1
@RequestBodyBodyPOST/PUT/DELETE/PATCHjson{“id”:1}

参考资料:Required request parameter ‘xxx‘ for method parameter type xxxx is not present 解决方式_汤米•谢尔比的博客-CSDN博客

更多推荐