这是我的ajax请求
var dataModel = {name1:"value1", name2:"value2"};
$.ajax({
url: "/testURL",
type: "POST",
async: false,
contentType: "application/json",
data: dataModel,
success: function(response) {
}
})
这是我在spring xml
中的相关摘录<annotation-driven>
<!-- Message converters are added to use custom object mapper in MappingJackson2HttpMessageConverter.
StringHttpMessageConverter is required to avoid MappingJackson2HttpMessageConverter from converting a string into json.
-->
<message-converters>
<beans:bean
class="org.springframework.http.converter.StringHttpMessageConverter">
</beans:bean>
<beans:bean
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<beans:property name="objectMapper" ref="jacksonObjectMapper"/>
</beans:bean>
</message-converters>
</annotation-driven>
这是我的控制器映射
@RequestMapping(value = "/testURL", method = { RequestMethod.POST })
public String add(HttpServletRequest request, @RequestBody CustomObject customObject) throws Exception {}
但我的要求甚至没有达到控制器。一旦我删除@RequestBody CustomObject customObject
,它就会起作用。但我想将json请求映射到
具有@RequestBody
的CustomObject未发生。 不确定我在这里缺少什么?
事实上,当我检查request.getParameterMap()
时,它显示为空,但只要我删除contentType: "application/json"
,我就会看到参数地图已填充,但仍然
然后得到以下错误
`The server refused this request because the request entity is in a format not supported by the requested resource for the requested method`
这是我的CustomObject定义
public class CustomObject implements Serializable {
private static final long serialVersionUID = 1L;
private String name1;
private String name2;
//getters and setters
}
已经通过JQuery, Spring MVC @RequestBody and JSON - making it work together但没有帮助
答案 0 :(得分:2)
实际上,当我检查request.getParameterMap()时,它显示为空但是 一删除contentType:“application / json”
这是对的。原因是contentType: "application/json"
jquery在内部将数据转换为字符串。所以没有请求参数。如果没有contentType: "application/json"
,则默认为contentType' is form data . So data sent is converted to request parameters based on delimiters
&amp; and
=`
另请尝试data: JSON.stringify(dataModel)
,它应该可以正常工作