spring mvc 支持如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void。
ModelAndView
1
2
3
4
5
|
@RequestMapping ( "/hello" ) public ModelAndView helloWorld() { String message = "Hello World, Spring 3.x!" ; return new ModelAndView( "hello" , "message" , message); } |
通過ModelAndView構造方法可以指定返回的頁面名稱,也可以通過setViewName()方法跳轉到指定的頁面
Map
1
2
3
4
5
6
7
|
@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方法。
View
可以返回pdf excel等,暫時沒詳細了解。
String
指定返回的視圖頁面名稱,結合設置的返回地址路徑加上頁面名稱后綴即可訪問到。
注意:如果方法聲明了注解@ResponseBody ,則會直接將返回值輸出到頁面。
1
2
3
4
|
@RequestMapping (value= "/showdog" ) public String hello1(){ return "hello" ; } |
1
2
3
4
5
6
|
@RequestMapping (value= "/print" ) @ResponseBody public String print(){ String message = "Hello World, Spring MVC!" ; return message; } |
返回json的例子(使用Jackson):
1
2
3
4
5
6
7
8
9
10
11
12
|
@RequestMapping ( "/load1" ) @ResponseBody public String load1( @RequestParam String name, @RequestParam String password) throws IOException{ System.out.println(name+ " : " +password); //return name+" : "+password; MyDog dog= new MyDog(); dog.setName( "小哈" );dog.setAge( "1歲" );dog.setColor( "深灰" ); ObjectMapper objectMapper = new ObjectMapper(); String jsonString=objectMapper.writeValueAsString(dog); System.out.println(jsonString); return jsonString; } |
void
如果返回值為空,則響應的視圖頁面對應為訪問地址
1
2
3
4
|
@RequestMapping ( "/index" ) public void index() { return ; } |
對應的邏輯視圖名為"index"
小結:
1.使用 String 作為請求處理方法的返回值類型是比較通用的方法,這樣返回的邏輯視圖名不會和請求 URL 綁定,具有很大的靈活性,而模型數據又可以通過 ModelMap 控制。
2.使用void,map,Model 時,返回對應的邏輯視圖名稱真實url為:prefix前綴+視圖名稱 +suffix后綴組成。
3.使用String,ModelAndView返回視圖名稱可以不受請求的url綁定,ModelAndView可以設置返回的視圖名稱。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/xiepeixing/p/4243801.html