使用ModelAndView向request域对象共享数据

在SpringMVC中向域对象共享数据的方法有多种

在底层中,这些类型的形参最终都是通过BindingAwareModelMap创建
他们的继承关系如下:
public class BindingAwareModelMap extends ExtendedModelMap{}
public class ExtendedModelMap extends ModelMap implements Model{}
public class ModelMap extends LinkedHashMap<String, Object>{}

1.通过ModelAndView向请求域共享数据

使用ModelAndView时,可以使用其model功能向请求域共享数据
使用view功能设置逻辑视图,但是控制器方法一定要将ModelAndView作为方法的返回值

2.使用Model向请求域共享数据
3.使用ModelMap向请求域共享数据
4.使用Map向请求域共享数据

其中2、3、4的方式底层也都是BindingAwareModelMap
其实无论使用哪种方式,底层模型与视图最后都会被封装到ModelAndView中

实现代码如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <hr>
    <a th:href="@{/test/mav}">测试通过ModelAndView向请求域共享数据</a><br>
    <a th:href="@{/test/model}">测试通过Model向请求域共享数据</a><br>
    <a th:href="@{/test/modelMap}">测试通过ModelMap向请求域共享数据</a><br>
    <a th:href="@{/test/map}">测试通过Map向请求域共享数据</a>
</body>
</html>
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>首页</title>
</head>
<body>
    <h1>success.html</h1>

    <p th:text="${testRequestScope}"></p>
</body>
</html>
package com.qcw.controller;
@Controller
public class TestScopeController {

    @RequestMapping("/test/mav")
    public ModelAndView testMAV(){
        /**
         * ModelAndView包含Model和View的功能
         *  Model:向请求域中共享数据
         *  View:设置逻辑视图实现页面跳转
         */
        ModelAndView mav = new ModelAndView();
        //向请求域中共享数据
        mav.addObject("testRequestScope","hello,ModelAndView");
        //设置逻辑视图
        mav.setViewName("success");
        return mav;
    }

    @RequestMapping("/test/model")
    public String testModel(Model model){

        System.out.println(model.getClass().getName());

        model.addAttribute("testRequestScope","hello,Model");
        return "success";
    }

    @RequestMapping("/test/modelMap")
    public String testModelMap(ModelMap modelMap){

        System.out.println(modelMap.getClass().getName());

        modelMap.addAttribute("testRequestScope","hello,ModelMap");
        return "success";
    }

    @RequestMapping("/test/map")
    public String testMap(Map<String ,Object> map){
        //org.springframework.validation.support.BindingAwareModelMap
        System.out.println(map.getClass().getName());

        map.put("testRequestScope","hello,map");
        return "success";
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值