14

我正在运行一个 Spring 3.1.2 应用程序。我有一个带有多种方法的 RESTful servlet。GET 方法在@PathVariables100% 的时间内工作得非常好(匹配、响应正确编组为基于 Accept 标头的 JSON 或 XML 等)。

但是 POST 方法根本不起作用。经过数小时的折腾和我能找到的所有其他 Spring 方面(所有修补都恢复了),我将其required范围缩小到@RequestParam. 这是我一直用来调查的简化测试方法:

@RequestMapping (value = "/bogus",
                 method = POST)
public @ResponseBody PassResponse bogus (
            @RequestParam (value = "test", required = false) String test) {
    // Just some handy garbage objects that marshal to JSON/XML
    UserResponse user = new UserResponse ();
    user.setName (test);
    AccountDetail detail = new AccountDetail (user,null);
    return new PassResponse (detail);
}

required=false:一切正常(接收并解释参数)。完全符合我的预期

required=true:(或未指定,因为这是默认值)我一直收到消息“ MissingServletRequestParameterException:必需的字符串参数'test'不存在

客户端视图:

必需=真

Request URL:http://localhost:8080/internal-project/rest/bogus
Request Method:POST
Status Code:400 Bad Request
Request Headersview source
Accept:application/json
Connection:keep-alive
Content-Length:12
Host:localhost:8080
Request Payload
test=LALALAA
Response Headersview source
Connection:close
Content-Length:971
Content-Type:text/html;charset=utf-8
Date:Wed, 24 Oct 2012 18:41:05 GMT
Server:Apache-Coyote/1.1

必需=假

Request URL:http://localhost:8080/internal-project/rest/bogus
Request Method:POST
Status Code:200 OK
Request Headersview source
Accept:application/json
Connection:keep-alive
Content-Length:12
Host:localhost:8080
Request Payload
test=LALALAA
Response Headersview source
Content-Type:application/json;charset=UTF-8
Date:Wed, 24 Oct 2012 18:44:03 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked

切换时运行的测试套件完全相同required,我可以看到参数正在传递。当参数是可选的时,Spring 会正确处理它。

如果有人以前遇到过这个问题或有任何想法,我很想听听他们的意见。将所需参数标记为可选,即使它有效,即使我评论它也是可怕的自我文档。再加上这种行为让我有点紧张。希望我只是在某个地方搞砸了一些东西......

4

1 回答 1

19

我认为你的Content-Type标题应该是。application/x-www-form-urlencoded

于 2012-10-24T19:16:13.560 回答