2013-10-27 25 views
13

我嘗試在Spring MVC中對我的控制器進行AJAX查詢。必需的字符串參數在Spring MVC中不存在錯誤

我的動作代碼是:

@RequestMapping(value = "events/add", method = RequestMethod.POST) 
public void addEvent(@RequestParam(value = "start_date") String start_date, @RequestParam(value = "end_date") String end_date, @RequestParam(value = "text") String text, @RequestParam(value = "userId") String userId){ 
    //some code  
} 

我的Ajax查詢:

$.ajax({ 
     type: "POST", 
     url:url, 
     contentType: "application/json", 
     data:  { 
       start_date: scheduler.getEvent(id).start_date, 
       end_date: scheduler.getEvent(id).end_date, 
       text: scheduler.getEvent(id).text, 
       userId: userId 
     }, 
     success:function(result){ 
     //here some code 
     } 
    }); 

但我得到了一個錯誤:

Required String parameter ''start_date is not present

爲什麼? 當我知道我提出它像(@RequestParam(value = "start_date") String start_date

UDP
現在我給404個 我班採取數據

public class EventData { 
    public String end_date; 
    public String start_date; 
    public String text; 
    public String userId; 
    //Getters and setters 
} 

我的JS AJAX調用是:

$.ajax({ 
    type: "POST", 
    url:url, 
    contentType: "application/json", 
    // data: eventData, 
    processData: false, 
    data: JSON.stringify({ 
     "start_date": scheduler.getEventStartDate(id), 
     "end_date": scheduler.getEventEndDate(id), 
     "text": scheduler.getEventText(id), 
     "userId": "1" 
    }), 

和控制器動作:

@RequestMapping(value = "events/add", method = RequestMethod.POST) 
public void addEvent(@RequestBody EventData eventData){  
} 

和JSON數據是:

end_date: "2013-10-03T20:05:00.000Z" 
start_date: "2013-10-03T20:00:00.000Z" 
text: "gfsgsdgs" 
userId: "1" 
+0

是否jquery將'data'元素序列化爲請求參數?作爲url編碼形式的參數? –

+0

它只是JS文件中的變量 – nabiullinas

+0

在這兩個示例中,您是否嘗試過實際檢查POST請求並確保它傳遞了所需的值?每種情況下顯示的是什麼? – woemler

回答

28

在服務器端,您希望您的請求參數作爲查詢字符串,但在客戶端發送一個JSON對象。要綁定一個json,你將需要創建一個包含所有參數的類,並使用@RequestBody註解來代替@RequestParam。

@RequestMapping(value = "events/add", method = RequestMethod.POST) 
public void addEvent(@RequestBody CommandBean commandBean){ 
    //some code 
} 

Here is更詳細的解釋。

+0

我試過了。它給我400錯誤錯誤請求 – nabiullinas

+0

你可以發佈你試圖發送的實際JSON嗎?你可以用Firebug或Chrome/Chromium來捕捉它。 – gadget

+1

您可以編寫,我如何在Google Chrome瀏覽器中看到它? – nabiullinas

0

我有同樣的問題..我解決它在發佈請求指定配置PARAMS:

var config = { 
    transformRequest : angular.identity, 
    headers: { "Content-Type": undefined } 
} 

$http.post('/getAllData', inputData, *config*).success(function(data,status) { 
    $scope.loader.loading = false; 
}) 

配置被我列入參數,它開始工作.. 希望它能幫助: )

相關問題