向域中设置对象的几总方式,ModelAndView既向域中设置了视图也设置了Model,其他的都以返回字符串的形式向域中设置视图
@Controller
public class ModelController {
//只有request是setAttribute,其他都是addAtribute
@RequestMapping("m01")
public ModelAndView m01() {
ModelAndView mv = new ModelAndView();
/**
* 模型参数 Model
* 视图:View
*/
mv.addObject("hello", "hello springmvc");
mv.setViewName("hello");
return mv;
}
/**
*这里和ModelAndView也有区别,ModelAndView返回的有视图和Model但是这里返回的String只代表乐视图
* @return
*/
@RequestMapping("m02")
public String m02(HttpServletRequest request) {
request.setAttribute("hello","hello m02");
//这里只需要返回视图名就可以
return "hello";
}
/**
* 用ModelMap 也可以向域中添加对象
* @param modelMap
* @return
*/
@RequestMapping("m03")
public String m03(ModelMap modelMap) {
modelMap.addAttribute("hello","hello m03");
//这里只需要返回视图名就可以,也就是返回视图
return "hello";
}
/**
* 用Model也可以实现向域中添加对象
* @param model
* @return
*/
@RequestMapping("m04")
public String m04(Model model) {
model.addAttribute("hello","hello m04");
//这里只需要返回视图名就可以,也就是返回视图
return "hello";
}
/**
* 用Model也可以实现向域中添加对象
*
* @param map
* @return
*/
@RequestMapping("m05")
public String m05(Map map) {
map.put("hello","hello m05");
//这里只需要返回视图名就可以,也就是返回视图
return "hello";
}
}