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()方法跳转到指定的页面 ,
使用addObject()设置需要返回的值,addObject()有几个不同参数的方法,可以默认和指定返回对象的名字。
调用addObject()方法将值设置到一个名为ModelMap的类属性,ModelMap是LinkedHashMap的子类。
Model、Map、ModelMap
一个模型对象,主要包含spring封装好的model和modelMap,以及Java.util.Map,当没有视图返回的时候视图名称将由requestToViewNameTranslator决定;Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类。
@RequestMapping(value = "/model")
public String createUser(Model model, Map model2, ModelMap model3) {
model.addAttribute("a", "a");
model2.put("b", "b");
model3.put("c", "c");
System.out.println(model == model2);
System.out.println(model2 == model3);
return "success";}
}
虽然此处注入的是三个不同的类型(Model model, Map model2, ModelMap model3),但三者是同一个对象。
AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter将使用BindingAwareModelMap作为模型对象的实现,即此处我们的形参(Model model, Map model2, ModelMap model3)都是同一个BindingAwareModelMap实例。
View
返回视图
String
@RequestMapping(method = RequestMethod.GET)
public String index(Model model) {
String retVal = "user/index";
List<User> users = userService.getUsers();
model.addAttribute("users", users);
return retVal;
}
String 指定返回的视图页面名称,结合设置的返回地址路径加上页面名称后缀即可访问到。
注意:如果方法声明了注解@ResponseBody ,则会直接将返回值输出到页面。
返回字符串代表的意义:
1):字符串代表逻辑视图名
真实的访问路径=“前缀”+逻辑视图名+“后缀”
2):代表redirect重定向
redirect的特点和servlet一样,使用redirect进行重定向那么地址栏中的URL会发生变化,同时不会携带上一次的request
public String testController(Model model){
return "redirect:path";//path代表重定向的地址
}
3):代表forward转发
通过forward进行转发,地址栏中的URL不会发生改变,同时会将上一次的request携带到写一次请求中去
public String testController(Model model){
return "forward:path";//path代表转发的地址
}
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 来返回一个对应的视图名称。如果这个时候需要模型的话,处理方法和返回字符串的情况是相同的。
返回这种结果的时候可以在Controller方法的形参中定义HTTPServletRequest和HTTPServletResponse对象进行请求的接收和响应