我正在尝试使用 Spring MVC 3.1 制作与这篇文章非常相似的东西:
JQuery、Spring MVC @RequestBody 和 JSON - 使其协同工作
并尝试将响应作为自定义类获取,例如示例中的“FooBar”。
我的 ajax 调用如下所示:
// var rule = "giveThisATry";
var rule = {
id : 1,
name : {
name1 : "1",
name2 : "2",
name3 : "3",
name4 : "4"
}
};
$.ajax({
url : "http://localhost:8080/spring2/save",
type : "POST",
dataType : "json",
//contentType : "application/json; charset=utf-8",
data : rule,
success : function(data) {
alert("success saveRule: " + data);
},
error : function(request, status, error) {
alert("error saveRule: " + request.responseText);
}
});
我的休息方法如下所示:
@RequestMapping(method = RequestMethod.POST, value = "/save")
public @ResponseBody MyClass save(@RequestBody MyClass instance, final HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
return MyDB.Save(instance);
}
现在无论我做什么,Spring 都不会将 ajax 调用映射到这个方法。另外,如果我在我的 ajax 调用中取消注释该行:
contentType : "application/json; charset=utf-8",
Chrome 会将 "request-method" 更改为 "OPTIONS" :
Request Method:OPTIONS
Status Code:200 OK
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:Origin, Content-Type, Accept
Access-Control-Request-Method:POST
Cache-Control:no-cache
Connection:keep-alive
Host:localhost:8080
Origin:http://127.0.0.1:8020
Pragma:no-cache
Referer:http://127.0.0.1:8020/JQueryPOC/src/index.html
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11
Response Headersview source
Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS
Content-Length:0
Date:Fri, 15 Jun 2012 15:07:19 GMT
Server:Apache-Coyote/1.1
现在我如何测试/调试/控制 MappingJacksonHttpMessageConverter 以便我可以使用 requestbody 或其他东西将 json 映射到 pojo?