[英]Spring MVC 3.2 +Jackson
我的要求很簡單,即我想編寫一個通用方法,該方法假定具有基於用戶請求的自動智能功能,它將生成響應,例如,如果我以html提交,則應生成html。 如果我以Json身份提交,則應生成Json。 下面是2個示例代碼,如果我編寫2個單獨的方法,它可以正常工作,但我想將其編寫為一種常用方法。
@Controller
public class Program1Controller {
@RequestMapping("/helloworld")
public @ResponseBody ModelAndView helloWord(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
@RequestMapping(value = DUMMY_EMP, method = RequestMethod.GET)
public @ResponseBody String getDummyEmployee() {
String message = "Welcome to TEST";
return message;
}
取而代之的是編寫2種單獨的方法,我想編寫一種應具有自動智能功能,以便根據用戶請求發送響應的方法。 在查詢GET上方,同樣我該如何進行POST。
您可以使用ajax處理該代碼。 在您的控制器中,您有2種不同的方法返回JSON,POST和GET,並且其RequestMapping可以具有相同的值。 例:
@RequestMapping(value = "/returnJSON", method = RequestMethod.GET)
public @ResponseBody String getDummyEmployee() {
String message = "Welcome to TEST";
return message;
}
@RequestMapping(value = "/returnJSON", method = RequestMethod.POST)
public @ResponseBody String getDummyEmployee2() {
String message = "Welcome to TEST";
return message;
}
對於返回HTML對象的對象也應該這樣做:
@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public @ResponseBody ModelAndView helloWord(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
@RequestMapping(value = "/helloworld", method = RequestMethod.POST)
public @ResponseBody ModelAndView helloWord2(){
String message = "Welcome to TEST";
return new ModelAndView("Test1", "message",message);
}
}
現在,在進行jquery ajax調用之前,將url作為參數傳遞並輸入:
$.ajax({
type: type,
url: url,
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.