Java org.springframework.web.bind.MissingServletRequestParameterException:所需的长参数“userId”不存在”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32221090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:10:56  来源:igfitidea点击:

org.springframework.web.bind.MissingServletRequestParameterException : Required Long parameter 'userId' is not present"

javascriptjavaspringspring-mvcpost

提问by Kumar Narendra

I am getting an exception while posting a call to Spring controller

我在发布对 Spring 控制器的调用时遇到异常

Exception is:

例外是:

 org.springframework.web.bind.MissingServletRequestParameterException : Required Long parameter 'userId' is not present"

My Javascript file is:

我的 Javascript 文件是:

$scope.removeUser = function(user){
        var userId = JSON.stringify(user);
        $http.post('/portal/settings/user/deletecustomeruser', userId).success(function(data){
                $scope.response = data;
            })
        }
    }

The Spring controller code is:

Spring 控制器代码是:

      @RequestMapping( value = "/user/deletecustomeruser", method = RequestMethod.POST , headers="Accept=application/json")
public @ResponseBody String deleteCustomerUser( @RequestParam (value = "userId") Long userId,
        HttpServletRequest request )
                throws Exception
                {
    String returnString = "";
    User user = userService.getUserById( userId );

When I put (required = false), then the userIdvalue became null. The JavaScript controller is clearly sending the "userId"in JSON format, but from the controller side there is some issue.

当我把(required = false),然后userId价值变成了null。JavaScript 控制器显然"userId"是以 JSON 格式发送的,但从控制器端来看存在一些问题。

I checked almost all questions in stackoverflow, but the given solutions didn't help.

我检查了 stackoverflow 中的几乎所有问题,但给定的解决方案没有帮助。

采纳答案by Anudeep Gade

You are expecting userId as request parameter on server side, but you are sending userId as request body in your client http post request,

您希望 userId 作为服务器端的请求参数,但您在客户端 http post 请求中将 userId 作为请求正文发送,

Change the client side to send userId as request parameter

更改客户端以发送 userId 作为请求参数

 $http.post('/portal/settings/user/deletecustomeruser?userId='+userId)

Or Change server side to use userId as request body in the controller

或更改服务器端以在控制器中使用 userId 作为请求正文

myControllerMethod (@RequestBody String userId)