Spring @MVC和带有x-www-form-urlencoded数据的@RequestBody批注? [英] Spring @MVC and the @RequestBody annotation with x-www-form-urlencoded data?
问题描述
我试图弄清楚为什么当Spring @Controller
处理程序方法包含@RequestBody
批注时,我无法从jQuery.ajax调用接收请求的原因.请考虑以下内容:
I am trying to figure out why I can't receive a request from a jQuery.ajax call when then Spring @Controller
handler method includes a @RequestBody
annotation. Consider the following:
HTML/JavaScript :
<form id="foo" action="/baz">
<input name="bar">
</form>
<script>
$(function() {
var $fooForm = $('#foo');
$fooForm.on('submit', function(evt) {
evt.preventDefault();
$.ajax({
url: $fooForm.action,
data: $fooForm.serialize(),
dataType: 'json',
type: 'POST',
success: function(data) { console.log(data); }
});
});
});
</script>
Java :
@RequestMapping(
value = "/baz",
method = RequestMethod.POST,
consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE,
produces = MediatType.APPLICATION_JSON_VALUE
)
public @ResponseBody SearchResults[] jqueryPostHandler(
@RequestBody FormDataObject formData)
{
return this.searchService.find(formData);
}
以上操作将失败,并带有@RequestBody
批注,并返回415错误(不会生成异常).但是,如果删除了@RequestBody
批注(即参数签名仅为FormDataObject formData
),则将调用该方法,并将JSON返回到JavaScript.
The above will fail with the @RequestBody
annotation present and return a 415 error (no exception will be generated). But if the @RequestBody
annotation is removed (i.e. the parameter signature is just FormDataObject formData
) then the method will be called and JSON will be returned to the JavaScript.
为什么会这样? POST
请求将数据包含在请求的正文中.注释处理不应该这样吗?
Why is this the case? A POST
request includes the data in the body of the request. Shouldn't the annotation process such a request?
我意识到我可以将JavaScript发送的内容类型更改为application/json
,将consumes
属性更改为MediaType.APPLICATION_JSON_VALUE
,以使注释正常工作.但是,为什么它不能与普通表单请求一起使用?
I realize that I could change the content type sent by the JavaScript to application/json
and the consumes
property to MediaType.APPLICATION_JSON_VALUE
to make the annotation work correctly. But why doesn't it work with a normal form request?
注意:我正在使用Spring 3.1.4.
Note: I am using Spring 3.1.4.
推荐答案
您是否尝试过登录'org.springframework.web'来查找返回状态代码的原因?在将其转换为415之前,应该引发并记录该异常.
Have you tried turning up logging on 'org.springframework.web' to find out the reason for the returned status code? There should be an exception raised and logged before it's translated to a 415.
如果要发送表单数据,为什么不直接删除@RequestBody.然后,您将使用将Servlet请求参数应用于对象字段的数据绑定(即@ModelAttribute).这比使用FormHttpMessageConverter更好.
Also if sending form data, why not just leave out the @RequestBody. You'll then be use data binding (i.e. @ModelAttribute) that will apply Servlet request parameters to object fields. This is preferable to using the FormHttpMessageConverter.
这篇关于Spring @MVC和带有x-www-form-urlencoded数据的@RequestBody批注?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!