文章目录

  • 目录
    • 1、springmvc使用ServletAPI向request作用域共享数据(原生态)
    • 2、springmvc使用ModelAndView向request作用域共享数据
    • 3、springmvc使用Model向request作用域共享数据
    • 4、springmvc使用map向request作用域共享数据
    • 5、springmvc使用ModelMap向request作用域共享数据

目录

1、springmvc使用ServletAPI向request作用域共享数据(原生态)

前端请求:

<a th:href="@{/test}">request作用域共享数据</a>

后台ServletAPI向request作用域共享数据:

 @RequestMapping("/test")public String testRequestByServletAPI(HttpServletRequest request) {//想request作用域中共享数据(存数据)request.setAttribute("testrequest", "servletapi");return "succeed";//request作用域中存数据转发到相应的页面进行取值}

页面取值:

<p th:text="${testrequest}"></p>

2、springmvc使用ModelAndView向request作用域共享数据

前端请求:

th:href="@{/testModelAndView}">使用ModelAndView向request作用域共享数据

后端使用ModelAndView向request作用域共享数据:

@RequestMapping("/testModelAndView")//使用ModelAndView时返回的方法类型必须是ModelAndViewpublic ModelAndView testModelAndView() {//创建ModelAndView对象ModelAndView mav = new ModelAndView();//使用ModelAndView共享数据,ModelAndView有两个作用//Model处理模型数据:向request作用域中共享数据,将底层获取的数据进行存储(或者封装)//最后将数据传递给Viewmav.addObject("ModelAndView", "hello,ModelAndView");//View视图设置视图名称:设置转向地址mav.setViewName("succeed");return mav;}

页面取值:

<p th:text="${ModelAndView}">

总结:
1、使用ModelAndView向request作用域中共享数据时。方法的返回值必须是ModelAndView。
2、ModelAndView,Model‘模型’进行数据的存储和封装跳转到View中
3、View”视图”,设置跳转的视图


3、springmvc使用Model向request作用域共享数据

前端:

<a th:href="@{/testModel}">使用Model向request作用域中共享数据

后台使用Model进行数据共享(存储数据):

@RequestMapping("/testModel")public String tsetModel(Model model){//形参的位置创建Model//使用Model向erquest中存储数据model.addAttribute("tsetModel","hello,model");return "succeed";}

取值:

<h1 th:text="${tsetModel}">

总结:

1、在方法形参的位置中创建Model对象进行数据的存储


4、springmvc使用map向request作用域共享数据

前端请求:

<a th:href="@{/testmap}">使用map向request作用域共享数据</a>

后端存储数据:

 @RequestMapping("/testmap")public String testmap(Map<String,Object > map) {map.put("map", "hellq,map");return "succeed";}

取值:

<h1 th:text="${map}"></h1>

总结:
1、方法形参的位置中创建Map map


5、springmvc使用ModelMap向request作用域共享数据

前端请求:

<a th:href="@{/testmodelmap}">使用ModelMap向request作用域共享数据</a>

使用ModelMap向request作用域中存储数据

@RequestMapping("/testmodelmap")public String testmodelmap(ModelMap modelMap) {modelMap.addAttribute("modelmap","hello,ModelMap");return "succeed";}

取值:
根据键值对取值

<h1 th:text="${modelmap}"></h1>