Spring @RequestParam参数未在POST方法中传递 [英] Spring @RequestParam arguments not being passed in POST method
问题描述
我在使用Spring和发布请求时遇到问题.我正在为Ajax调用设置控制器方法,请参见下面的方法定义
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
@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) {
....
无论我以哪种方式进行HTML调用,@RequestParam
参数的值始终为null.我还有许多其他看起来像这样的方法,主要的区别是其他方法是GET方法,而这个方法是POST.
No matter what way I make the HTML call, the values for the @RequestParam
parameters 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 @RequestParam
with a POST method?
我正在使用Spring 3.0.7.RELEASE-有人知道问题的原因是什么吗?
I'm using Spring version 3.0.7.RELEASE - Does anyone know what the cause of the problem may be?
Ajax代码:
$.ajax({
type:'POST',
url:"/comments/add.page",
data:{
uuid:"${param.uuid}",
type:"${param.type}",
text:text
},
success:function (data) {
//
}
});
推荐答案
问题原来是我调用该方法的方式.我的ajax代码正在传递请求正文中的所有参数,而不是将其作为请求参数传递,因此这就是我的@RequestParam
参数都为空的原因.我将ajax代码更改为:
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 @RequestParam
parameters were all empty. I changed my ajax code to:
$.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.
这篇关于Spring @RequestParam参数未在POST方法中传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!