栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC学习笔记——5.域对象共享数据

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC学习笔记——5.域对象共享数据

三个域对象:request、session、application简介

域对象的选择:可以实现功能,但范围尽可能小的域对象

1.使用servletAPI向request域对象共享数据

控制器方法:

index.html:

success.html:

2.使用ModelAndView向request域对象共享数据(SpringMVC)

ModelAndView: 两个功能1、向request域对象共享数据2、设置视图名称
当在控制器使用ModelAndView时,ModelAndView必须作为该方法的返回值返回

    @RequestMapping("/testModelAndView")
    public ModelAndView testModelAndView(){
        
        ModelAndView mav = new ModelAndView();
        //向请求域共享数据
        mav.addObject("testRequestScope", "hello,ModelAndView");
        //设置视图,实现页面跳转
        mav.setViewName("success");
        return mav;
    }
3.使用Model向request域对象共享数据(SpringMVC)
    @RequestMapping("/testModel")
    public String testModel(Model model){
        model.addAttribute("testRequestScope", "hello,Model");
        return "success";
    }
4.使用map向request域对象共享数据(SpringMVC)

在形参位置创建Map集合,往Map所存放的数据就是往域对象中共享的数据。

    @RequestMapping("/testMap")
    public String testMap(Map map){
        map.put("testRequestScope","Hello,map");
        return "success";
    }
5.使用ModelMap向request域对象共享数据(SpringMVC)
    @RequestMapping("/testModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testRequestScope","hello ,modelMap");
        return "success";
    }
6.Model、ModelMap、Map的关系

Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

public class BindingAwareModelMap extends ExtendedModelMap {}
public class ExtendedModelMap extends ModelMap implements Model {}
public interface Model {}
public class ModelMap extends LinkedHashMap {}
public class LinkedHashMap extends HashMap implements Map {}

BindingAwareModelMap类继承了ExtendedModelMap类 ;
在ExtendedModelMap类中继承了ModelMap 类和实现了Model 接口;
而 ModelMap 继承了LinkedHashMap类,LinkedHashMap类又是Map接口的实现类;
因此,Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

ModelAndView是SpringMVC中建议使用的对象,包含两个功能Model和View;使用其它方法向请求域共享数据,最终都会将模型数据和当前视图信息封装到ModelAndView里面。

7.向session域共享数据

建议使用原生API

@RequestMapping("/testSession")
public String testSession(HttpSession session){
session.setAttribute("testSessionScope", "hello,session");
return "success";
}
8.向application域共享数据
    @RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplication","hello,application");
        return "success";
    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937180.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号