2012-06-15 47 views
0

我試圖使用Spring MVC 3.1做出非常相似,這個帖子的東西POJO:映射JSON使用MappingJacksonHttpMessageConverter和POST

JQuery, Spring MVC @RequestBody and JSON - making it work together

,並試圖獲得響應的自定義類,例如「 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); 
} 

現在不管我做什麼,春天不會Ajax調用映射到這個方法。 另外,如果我在我的Ajax調用取消對該行:

contentType : "application/json; charset=utf-8", 

瀏覽器將改變「請求方法」到「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?

回答

1

一兩件事,我看到你有到rule轉換成JSON字符串 - 這個插件可以幫助你:http://code.google.com/p/jquery-json/ data : $.toJSON(rule)

+0

謝謝六必居。其實我的代碼正在遭受你指出的其中一個錯誤。另一個原因是我試圖在將服務和客戶端代碼放入同一個項目後解決了跨域ajax調用。另外我重寫了我的FooBar類的默認構造函數,這導致了序列化中的問題。 – nilgun