当Controller组件处理后,向jsp页面传值,
1:使用HttpServletRequest 和 Session 然后setAttribute(),就和Servlet中一样
2:使用ModelAndView对象
3:使用ModelMap对象
4:使用@ModelAttribute注解
ModelAndView:
ModelAndView有两个作用,通过ModelAndView构造方法可以指定返回的页面名称,也可以通过setViewName()方法跳转到指定的页面。用于传递控制方法处理结果数据到结果页面,也就是说我们把需要在结果页面上需要的数据放到ModelAndView对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。通过以下方法向页面传递参数: addObject(String key,Object value);
@RequestMapping("/test")
public ModelAndView show1(HttpServletRequest request, HttpServletResponse response) throwsException {
ModelAndView modelAndView = new ModelAndView("/test");
modelAndView.addObject("type", "type");
return modelAndView;
}
ModelMap :
ModelMap对象主要用于传递控制方法处理数据到结果页面,也就是说我们把结果页面上需要的数据放到ModelMap对象中即可,他的作用类似于request对象的setAttribute方法的作用,用来在一个请求过程中传递处理的数据。ModelMap数据会利用HttpServletRequest的Attribute传值到页面中。
@RequestMapping("/test")
public String test(ModelMap modelMap){
modelMap.addAttribute("name3", "name3");
modelMap.put("name4", "name4");
return "test";
}
ModelMap API:http://www.apihome.cn/api/spring/ModelMap.html
Model :
Model 是一个接口, 其实现类为ExtendedModelMap,继承了ModelMap类。Model数据会利用HttpServletRequest的Attribute传值到页面中。
@RequestMapping("/test")
public String test(Model model){
model.addAttribute("name1", "name1");
return "test"";
}
@ModelAttribute:
在Controller方法的参数部分或Bean属性方法上使用@ModelAttribute数据会利用HttpServletRequest的Attribute传值到页面中。被@ModelAttribute注释的方法会在此controller每个方法执行前被执行,因此对于一个controller映射多个URL的用法来说,要谨慎使用。
@RequestMapping("/test")
public String login(@ModelAttribute("user") User user){
return "test";
}
@ModelAttribute("name")
public String getName(){
return name;
}
Session:
利用HttpServletReequest的getSession()方法
@RequestMapping("/test")
public String login(HttpServletRequest request){
HttpSession session = request.getSession();
session.setAttribute("user",user);
return "test";
}
自定义Map:
@ResponseBody
@RequestMapping(value = "/testMap", method = RequestMethod.POST)
public Map<String, Object> testMap(HttpServletRequest request) {
Map<String, Object> result = new HashMap<String, Object>();
boolean flag = false;
....
result.put("status", flag);
return result;
}
Spring MVC 默认采用的是转发来定位视图,如果要使用重定向,可以如下操作
1:使用RedirectView
public ModelAndView test(){
RedirectView view = new RedirectView("test");
return new ModelAndView(view);
}
2:使用redirect:前缀public String test(){
//TODO
return "redirect:test";
}
spring mvc处理方法支持如下的返回方式:ModelAndView, Model, ModelMap, Map,View, String, void