Spring复习——day11_SpringMVC_域对象共享数据

发布于:2022-10-16 ⋅ 阅读:(983) ⋅ 点赞:(0)

目录

 

5、域对象共享数据

5.1、使用ServletAPI向request域对象共享数据

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

5.3、使用Model向request域对象共享数据

5.4、使用Map向request域对象共享数据

5.5、使用ModelMap向request域对象共享数据

5.6、Model、ModelMap、Map的关系

5.7、向session域共享数据

5.8、向application域共享数据


5、域对象共享数据

5.1、使用ServletAPI向request域对象共享数据

    @RequestMapping("/testServletAPI")
    public String testServletAPI(HttpServletRequest request){
        request.setAttribute("testScope", "hello,servletAPI");
        return "success";
    }

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

        使用ModelAndView向请求域共享数据时,可以使用其Model功能向请求域共享数据,使用

View功能设置逻辑视图,但是控制器方法一定要将ModelAndView作为方法的返回值。

    @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;
    }

5.3、使用Model向request域对象共享数据

    @RequestMapping("/test/model")
    public String testModel(Model model){
        //输出:org.springframework.validation.support.BindingAwareModelMap
        System.out.println(model.getClass().getName());
        model.addAttribute("testRequestScope", "hello,Model");
        return "success";
    }

5.4、使用Map向request域对象共享数据

    @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";
    }

5.5、使用ModelMap向request域对象共享数据

    @RequestMapping("/test/modelMap")
    public String testModelMap(ModelMap modelMap){
        //输出为:org.springframework.validation.support.BindingAwareModelMap
        System.out.println(modelMap.getClass().getName());
        modelMap.addAttribute("testRequestScope", "hello,ModelMap");
        return "success";
    }

5.6、Model、ModelMap、Map的关系

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

public interface Model{}

public class ModelMap extends LinkedHashMap<String, Object> {}

public class ExtendedModelMap extends ModelMap implements Model {}

public class BindingAwareModelMap extends ExtendedModelMap {}

5.7、向session域共享数据

    @RequestMapping("/test/session")
    public String testSession(HttpSession session){
        session.setAttribute("testSessionScope", "hello,session");
        return "success";
    }

5.8、向application域共享数据

    @RequestMapping("/test/application")
    public String testApplication(HttpSession session){
        ServletContext servletContext = session.getServletContext();
        servletContext.setAttribute("testApplicationScope", "hello,application");
        return "success";
    }