spring mvc 支持以下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void。spring
ModelAndViewjson
@RequestMapping("/hello") public ModelAndView helloWorld() { String message = "Hello World, Spring 3.x!"; return new ModelAndView("hello", "message", message); }
经过ModelAndView构造方法能够指定返回的页面名称,也能够经过setViewName()方法跳转到指定的页面mvc
Mapapp
@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方法。jsp
View url
能够返回pdf excel等,暂时没详细了解。spa
String excel
指定返回的视图页面名称,结合设置的返回地址路径加上页面名称后缀便可访问到。
注意:若是方法声明了注解@ResponseBody ,则会直接将返回值输出到页面。code
@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):blog
@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
若是返回值为空,则响应的视图页面对应为访问地址
@RequestMapping("/index") public void index() { return; }
对应的逻辑视图名为"index"
小结:
1.使用 String 做为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求 URL 绑定,具备很大的灵活性,而模型数据又能够经过 ModelMap 控制。
2.使用void,map,Model 时,返回对应的逻辑视图名称真实url为:prefix前缀+视图名称 +suffix后缀组成。
3.使用String,ModelAndView返回视图名称能够不受请求的url绑定,ModelAndView能够设置返回的视图名称。