一、可选类型
spring mvc 支持如下的返回方式:1、ModelAndView
2、Model
3、ModelMap
4、Map
5、View
6、String
7、Void
二、具体介绍
1、ModelAndView
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView("/user/index");
modelAndView.addObject("xxx", "xxx");
return modelAndView;
}
@RequestMapping(method=RequestMethod.GET)
public ModelAndView index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("xxx", "xxx");
modelAndView.setViewName("/user/index");
return modelAndView;
}
对于ModelAndView构造函数可以指定返回页面的名称,也可以通过setViewName方法来设置所需要跳转的页面;返回的是一个包含模型和视图的ModelAndView对象;对于ModelAndView类的属性和方法
2、Model
一个模型对象,主要包含spring封装好的model和modelMap,以及java.util.Map,当没有视图返回的时候视图名称将由requestToViewNameTranslator决定;3、ModelMap
待续4、Map
@RequestMapping(method=RequestMethod.GET)
public Map<String, String> index(){
Map<String, String> map = new HashMap<String, String>();
map.put("1", "1");
//map.put相当于request.setAttribute方法
return map;
}
响应的view应该也是该请求的view。等同于void返回。
5、View
这个时候如果在渲染页面的过程中模型的话,就会给处理器方法定义一个模型参数,然后在方法体里面往模型中添加值。可以返回pdf excel等,暂时没详细了解。6、String
对于String的返回类型,更多是是配合Model来使用的;注意:如果方法声明了注解@ResponseBody ,则会直接将来将内容或者对象作为HTTP响应正文返回(适合做即时校验);
@RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
String retVal = "user/index";
List<User> users = userService.getUsers();
model.addAttribute("users", users);
return retVal;
}
@RequestMapping(value="/print")
@ResponseBody
public String print(){
String message = "Hello World, Spring MVC!";
return message;
}
返回json的例子(使用Jackson):@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;
}
7、Void
当返回类型为Void的时候,则响应的视图页面为对应着的访问地址@Controller
@RequestMapping(value="/type")
public class TypeController extends AbstractBaseController{
@RequestMapping(method=RequestMethod.GET)
public void index(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("xxx", "xxx");
}
}
返回的结果页面还是:/type这个时候我们一般是将返回结果写在了HttpServletResponse 中了,如果没写的话,spring就会利用RequestToViewNameTranslator 来返回一个对应的视图名称。如果这个时候需要模型的话,处理方法和返回字符串的情况是相同的。
小结:
1.使用 String 作为请求处理方法的返回值类型是比较通用的方法,这样返回的逻辑视图名不会和请求 URL 绑定,具有很大的灵活性,而模型数据又可以通过 ModelMap 控制。2.使用void,map,Model 时,返回对应的逻辑视图名称真实url为:prefix前缀+视图名称 +suffix后缀组成。
3.使用String,ModelAndView返回视图名称可以不受请求的url绑定,ModelAndView可以设置返回的视图名称。