当前位置 : 主页 > 编程语言 > java >

怎样将控制层数据传到视图

来源:互联网 收集:自由互联 发布时间:2022-10-26
怎么将控制层的数据传回到视图 Model ModelMap Map ModelAndView 默认都是存入request域中 1.通过Model存入 存入 //方式1 存入model @RequestMapping("/selectUser") public String selectUser(Model model) { User user=new

怎么将控制层的数据传回到视图
Model ModelMap Map ModelAndView 默认都是存入request域中

1.通过Model存入
存入

//方式1 存入model
@RequestMapping("/selectUser")
public String selectUser(Model model)
{
User user=new User("zhangsan","123",23,new Address("湖北","武汉","汉口大道100号"));

model.addAttribute("user",user);

return "showUser";

}

访问

姓名:${user.uname}<br>

2.通过ModelMap或Map存入

//方式二 存入map或者modelmap
@RequestMapping("/selectUser2")
public String selectUser2(ModelMap map)
{
User user=new User("zhangsan2","123",23,new Address("湖北","武汉","汉口大道100号"));

map.put("user",user);

return "showUser";
}

@RequestMapping("/selectUser3")
public String selectUser3(Map map)
{
User user=new User("zhangsan3","123",23,new Address("湖北","武汉","汉口大道100号"));

map.put("user",user);

return "showUser";
}

取值:

同上

3.通过ModelAndView存入

//方式3 存入ModelAndView
@RequestMapping("/selectUser4")
public ModelAndView selectUser4()
{
User user=new User("zhangsan4","123",23,new Address("湖北","武汉","汉口大道100号"));

//创建ModelAndView对象
ModelAndView modelAndView=new ModelAndView();

//将需要传递到视图页面的数据存入
modelAndView.addObject("user",user);
//将需要转发的页面存入
modelAndView.setViewName("showUser");

return modelAndView;
}

@RequestMapping("/selectUser5")
public ModelAndView selectUser5()
{
User user=new User("zhangsan5","123",23,new Address("湖北","武汉","汉口大道100号"));

List<User> userList=new ArrayList<User>();
userList.add(new User("zhangsan1","123",23,new Address("湖北","武汉","汉口大道100号")));
userList.add(new User("zhangsan2","123",23,new Address("湖北","武汉","汉口大道100号")));
userList.add(new User("zhangsan3","123",23,new Address("湖北","武汉","汉口大道100号")));

ModelAndView modelAndView=new ModelAndView();

ModelMap modelMap=new ModelMap();
modelMap.addAttribute("user",user);
modelMap.addAttribute("userList",userList);

//将所有的数据 通过 map集合的方式存入
modelAndView.addAllObjects(modelMap);

modelAndView.setViewName("showUser2");

return modelAndView;

}

取值 同上

上一篇:SSM综合案例之角色管理实战
下一篇:没有了
网友评论