2015-11-03 69 views
1

我想學習Spring框架爲我未來的項目創建RESTful web服務。到目前爲止,我已經嘗試使用GET並使用簡單的Ajax請求毫無問題地使用它。我也嘗試使用查詢字符串輸入參數。春季REST web服務與JSON參數使用jquery AJAX

截至目前我正在嘗試創建一個接收POST請求的端點。我一直在研究一些日子,但無濟於事(有些內容對於像我這樣的初學者來說太複雜了)。

這裏是我的簡單的代碼:

的Java春

@RequestMapping(value = "/test", method = RequestMethod.POST) 
@ResponseBody 
public String testString(String jsonString) 
{ 
     System.out.println(jsonString); 
     return jsonString; 
} 

阿賈克斯

var data = {"name":"John Doe"} 
    $.ajax({ 
       url: "http://localhost:8080/springrestexample/test", 
       method:"POST", 
       data:data, 
       dataType:'text', 
       success: function(data) { 
       alert(data);         
       }, 
       error: function(xhr, status, errorThrown) { 
        alert("Error:" + errorThrown + status); 
       } 
     }); 

我試圖調試和tomcat好像我不傳遞將TestString任意值。我是否需要在我的java代碼中添加一些內容?

+0

問題是什麼?是'jsonString' null?看看'@ RequestBody' – sidgate

+0

'data:{jsonString:data},'改變爲這個也設置了一個有效的'contentType:'application/json'' – Jai

+0

是的,jsonString始終爲空。我也試着改名爲jsonString仍然沒有正確的迴應 –

回答

0

@RequestMapping只將您的方法映射到某個url。 訪問數據,你需要@RequestParam註釋獲取數據,如:

@RequestMapping(value = "/test", method = RequestMethod.POST) 
@ResponseBody 
public String testString(@RequestParam("name") String jsonString) 
{ 
    System.out.println(jsonString); 
    return jsonString; 
} 

this手冊更多的例子。

+0

所以我可以使用@RequestParam沒有查詢字符串? –

+0

'@ RequestParam'存儲請求中的變量。無論是「GET」還是「POST」。你也可以使用'@ PathVariable'。參考手冊。 –

+0

會試試這個謝謝 –

0

既然你逝去的數據轉換成身體從你的Ajax請求,所以你需要檢索從

@RequestBody

像這樣的參數之前添加此註釋;

public String testString(@RequestBody String jsonString) { 
    System.out.println(jsonString); 
    return jsonString; 
} 

和你做:)