Spring @RequestParam 参数未在 POST 方法中传递

问题描述 投票:0回答:1

我遇到了 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) {
        ....

无论我以何种方式进行 HTML 调用,

@RequestParam
参数的值始终为 null。我还有很多其他的方法,看起来像这样,主要区别是其他的是 GET 方法,而这个是 POST 方法。是否无法将
@RequestParam
与 POST 方法一起使用?

我正在使用 Spring 版本 3.0.7.RELEASE - 有谁知道问题的原因可能是什么?


Ajax代码:

$.ajax({
    type:'POST',
    url:"/comments/add.page",
    data:{
        uuid:"${param.uuid}",
        type:"${param.type}",
        text:text
    },
    success:function (data) {
        //
    }
});
spring spring-mvc
1个回答
19
投票

问题出在我调用该方法的方式上。我的 ajax 代码传递的是请求正文中的所有参数,而不是作为请求参数,所以这就是为什么我的

@RequestParam
参数都是空的。我将我的ajax代码更改为:

$.ajax({
    type: 'POST',
    url: "/comments/add.page?uuid=${param.uuid}&type=${param.type}",
    data: text,
    success: function (data) {
        //
    }
});

我还更改了控制器方法以从请求正文中获取文本:

@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) {

现在我得到了我期望的参数。

© www.soinside.com 2019 - 2024. All rights reserved.