spring mvc 的返回類型:ModelAndView, Model, ModelMap, Map, String, void。
ModelAndView
@RequestMapping("/hello")
public ModelAndView helloWorld() {
String message = "Hello World, Spring 3.x!";
return new ModelAndView("hello", "message", message);
}
通過ModelAndView構造方法可以指定返回的頁面名稱,也可以通過setViewName()方法跳轉到指定的頁面
Map
@RequestMapping("/demo2/show")
public Map<String, String> getMap() {
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value-1");
map.put("key2", "value-2");
return map;
}
在jsp頁面中可直通過${key1}獲得到值, map.put()相當於request.setAttribute方法。
String(常用)
指定返回的視圖頁面名稱,結合設置的返回地址路徑加上頁面名稱後綴即可訪問到。
注意:如果方法聲明瞭註解@ResponseBody ,則會直接將返回值輸出到頁面。
@RequestMapping(value="/showdog")
public String hello1(){
return "hello";
}
@RequestMapping(value="/print")
@ResponseBody
public String print(){
String message = "Hello World, Spring MVC!";
return message;
}
返回json的例子(使用Jackson):
/**
* testJson
* @param model
* @return
*/
@ResponseBody
@RequestMapping(value = "testJson", method = RequestMethod.POST)
public String test(String userName) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("status", "0");
jsonObject.put("status_text", "正常");
System.out.println(jsonObject.toString());
return jsonObject.toString();
}
void
如果返回值爲空,則響應的視圖頁面對應爲訪問地址
@RequestMapping("/index")
public void index() {
return;
}
對應的邏輯視圖名爲”index”。
小結:
1.使用 String 作爲請求處理方法的返回值類型是比較通用的方法,這樣返回的邏輯視圖名不會和請求 URL 綁定,具有很大的靈活性,而模型數據又可以通過 ModelMap 控制。
2.使用void,map,Model 時,返回對應的邏輯視圖名稱真實url爲:prefix前綴+視圖名稱 +suffix後綴組成。
3.使用String,ModelAndView返回視圖名稱可以不受請求的url綁定,ModelAndView可以設置返回的視圖名稱。
4.當使用重定向傳遞參數中文亂碼問題解決:把中文的參數放到model裏傳遞。
model.addAttribute("queryName", user.getQueryName());
//return "redirect:userManage.shtml?queryName="+user.getQueryName()";
return "redirect:userManage.shtml";