【SpringMVC】返回视图中包含数据(ModelAndView)

在普通的servlet项目中,Controller获取了数据,需要在视图显示,需要显示的调用request.setAttribute()等方法

在SpringMVC中,使用ModelAndView、ModelMap,Model,Map。

以下四种方式都是放在request域中,

如果放在Session中,在类名前加上@SessionAttributes("student"),@SessionAttributes("student1")这样的注解,注解中为放入request域中名字(如果需要在session中放入所有Student类型的对象,@SessionAttributes(types=Student.class)或@SessionAttributes(types= {Student.class,Adress.class}))

ModelAndView示例 方法:

    public ModelAndView testModelAndView(){
        // Model:M View:V
        ModelAndView modelAndView = new ModelAndView("success");
        Student student = new Student();
        student.setId(1);
        student.setName("zs");
        // equals to : request.setAttribute("student",student);
        modelAndView.addObject("student",student);
        return modelAndView;

    }

访问链接:

<a href="handler/testModelAndView">testModelAndView</a>

放在request域中,页面输出:${requestScope.student.id}

 

ModelMap方式:

    @RequestMapping(value = "testModelMap")
    public String testModelMap(ModelMap modelMap) {
        Student student = new Student();
        student.setId(123);
        student.setName("qwer");
        modelMap.put("student2", student);
        return "success";
    }

 

Map方式:

    @RequestMapping("testMap")
    public String testMap(Map<String, Object> map) {
        Student student = new Student();
        student.setId(2);
        student.setName("asd");
        map.put("student3", student);
        return "success";
    }

 

Model方式:

    @RequestMapping("testModel")
    public String testModel(Model model) {
        Student student = new Student();
        student.setId(3);
        student.setName("ttt");

        model.addAttribute("student3", student);
        return "success";
    }

 

转载于:https://www.cnblogs.com/to-red/p/11342427.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值