我正在运行Spring 3.1.2应用程序。我有一个RESTful servlet,有许多方法。 GET方法工作得非常好(@PathVariables
匹配,响应在100%的时间内根据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会正确处理它。
如果有人之前碰过这个或有任何想法,我很乐意听到。将所需参数标记为可选参数即使可行,也是可怕的自我文档,即使我发表评论。此外,这种行为让我有点紧张。希望我在某个地方搞砸了......
答案 0 :(得分:19)
我认为Content-Type
标题应为application/x-www-form-urlencoded
。