Spring @RequestParam 参数未在 POST 方法中传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14006619/
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
Spring @RequestParam arguments not being passed in POST method
提问by John Farrelly
I'm having a problem with Spring and a post request. I'm setting up an controller method for an Ajax call, see the method definition below
我遇到了 Spring 和 post 请求的问题。我正在为 Ajax 调用设置控制器方法,请参阅下面的方法定义
@RequestMapping(value = "add.page", method = RequestMethod.POST)
@ResponseBody
public Object createComment(
@RequestParam(value = "uuid", required = false) String entityUuid,
@RequestParam(value = "type", required = false) String entityType,
@RequestParam(value = "text", required = false) String text,
HttpServletResponse response) {
....
No matter what way I make the HTML call, the values for the @RequestParamparameters are always null. I have many other methods that looks like this, the main difference is that the others are GET methods, whereas this one is a POST. Is it not possible to use @RequestParamwith a POST method?
无论我以何种方式进行 HTML 调用,@RequestParam参数的值始终为空。我有许多其他方法看起来像这样,主要区别在于其他方法是 GET 方法,而这个方法是 POST。不能@RequestParam与 POST 方法一起使用吗?
I'm using Spring version 3.0.7.RELEASE - Does anyone know what the cause of the problem may be?
我正在使用 Spring 版本 3.0.7.RELEASE - 有谁知道问题的原因可能是什么?
Ajax code:
阿贾克斯代码:
$.ajax({
type:'POST',
url:"/comments/add.page",
data:{
uuid:"${param.uuid}",
type:"${param.type}",
text:text
},
success:function (data) {
//
}
});
回答by John Farrelly
The problem turned out to be the way I was calling the method. My ajax code was passing all the parameters in the request body and not as request parameters, so that's why my @RequestParamparameters were all empty. I changed my ajax code to:
问题原来是我调用方法的方式。我的 ajax 代码传递了请求正文中的所有参数,而不是作为请求参数,所以这就是为什么我的@RequestParam参数都是空的。我将我的 ajax 代码更改为:
$.ajax({
type: 'POST',
url: "/comments/add.page?uuid=${param.uuid}&type=${param.type}",
data: text,
success: function (data) {
//
}
});
I also changed my controller method to take the text from the request body:
我还更改了我的控制器方法以从请求正文中获取文本:
@RequestMapping(value = "add.page", method = RequestMethod.POST)
@ResponseBody
public Object createComment(
@RequestParam(value = "uuid", required = false) String entityUuid,
@RequestParam(value = "type", required = false) String entityType,
@RequestBody String text,
HttpServletResponse response) {
And now I'm getting the parameters as I expect.
现在我得到了我期望的参数。

