2016-11-08 85 views
1

我將JS數組項傳遞給彈簧控制器。我有這種模式在JS:對象數組來自Ajax的彈簧控制器字符串

function Row() { 
      this.id = 0; 
      this.rulingValue = ''; 
      this.rulingType = ''; 
      this.dateStart = ''; 
      this.dateEnd = ''; 
     } 

我排陣 - var jsonData = [];

然後我填這個數組。並設置爲

var oMyForm = new FormData(); 
oMyForm.append("items", jsonData); 

在Spring控制器我希望這個數組一樣List<Item>

@Data 
public class Item { 
    private String id; 
    private String rulingValue; 
    private String rulingType; 
    private String dateStart; 
    private String dateEnd; 
} 

@RequestParam("items") List<Item> items 

但我的項目參數作爲字符串到達​​。我怎樣才能得到這個數組像List<Item>

+0

使用'@ RequestBody'。 '@ RequestParam'查詢字符串。 – sura2k

回答

0

Springs向控制器發送JSON的首選方式是作爲主體有效載荷而不是表單參數。要做到這一點,你只需要做三件事:

  1. 請確保您在類路徑中有一個JSON庫,例如, fasterxml.jackson。
  2. 確保您的JSON有效負載通過POST請求通過HTTP內容類型「application/json」發送。
  3. 使用@RequestBody在Controller處理程序方法中標註接收參數。

    getItems(@RequestBody列表項)

一個完整的例子可以在這裏找到:http://www.beabetterdeveloper.com/2013/07/spring-mvc-requestbody-and-responsebody.html

如果你留在發送數據的形式參數,你就必須編寫自定義屬性請按照此處指示的行編輯:JSON parameter in spring MVC controller。這非常困難,需要額外的代碼。