在Spring MVC(我與3.0.2工作),兩個HTTP方法總是(或主要是因爲在我看來)保留(即與適當的處理程序映射),這是GET and POST如如何處理Spring MVC中的Ajax請求?
@RequestMapping(method=RequestMethod.GET)
public String showForm(Map model)
{
//Usually retrieve data from the database when the page is loaded.
return "admin_side/Temp";
}
上面的方法在GET請求時被調用。
@RequestMapping(method=RequestMethod.POST)
public String onSubmit(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult error, Map model, HttpServletRequest request, HttpServletResponse response)
{
//Perform some basic operations with the database like insert, update or delete when the form is submitted (by clicking a submit button or so).
return "admin_side/Temp";
}
上述方法時的POST請求時被調用。假設Spring控制器被指定爲@RequestMapping(value="admin_side/Temp")
註釋。
現在,如果我需要使用Ajax並且需要執行與前面的方法不同的功能,會發生什麼?我既不能處理與GET方法也不與POST方法的另一種方法,因爲有已被映射處理程序(包括HTTP方法,GET和POST保留分別處理showForm()
和onSubmit()
方法)。
爲了演示起見,我用了method=RequestMethod.PUT
方法使用Ajax如
@RequestMapping(method=RequestMethod.PUT)
public @ResponseBody String getStateList(@ModelAttribute("tempBean") @Valid TempBean tempBean, BindingResult error, HttpServletRequest request, HttpServletResponse response)
{
return "Message";
}
和它的工作如預期,但我覺得它應該不是最好的解決方案。如果你有這樣一個場景(實際上,它對我來說似乎很平常),你如何處理Spring MVC中的Ajax請求?我應該(總是)使用RequestMethod.PUT
? (或什麼是春季適合於Ajax的最好的HTTP方法?)
有沒有一種方法來映射多個方法與在同一個控制器相同的HTTP方法(一個明顯的答案應該是沒有)?同樣,當您需要在Spring MVC中使用Ajax時,您使用了哪種方法?希望你遵循我的意思!對於我來說,我的英語很困難,因爲我的英語處於初始階段。
謝謝!使用其他網址完成。現在,我需要使用Ajax從Spring控制器中檢索數據(通常是'List >')。我現在不知道,但Spring MVC 3.0.2應該支持像JSON這樣的機制。你知道嗎?我的意思是,如果你在Spring MVC中使用了這些東西,你有鏈接嗎?您可能會拒絕我的請求,因爲這不是原來的問題。謝謝。 – Tiny 2012-08-05 20:01:15
@Tiny這裏是一個使用Jackson庫的例子:http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/ – toniedzwiedz 2012-08-05 22:20:16