35.域对象共享数据

域对象共享数据

Thymeleaf获取值的写法:

  • request作用域:

  • session作用域及以上:

清除session作用域数据写法:

  • session.invalidate()

向request域对象共享数据

使用ServletAPI

SharedDataController.java

    @RequestMapping("/testServletAPI")
    public String testServletAPI(HttpServletRequest request){
        request.setAttribute("Servlet","API");
        return "success";
    }

使用ModelAndView

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

方法体一定要将ModelAndView设置为返回值

使用Model

    @RequestMapping("/testRequestModel")
	//导入的是包为org.springframework.ui.Model
    public String testModel(Model model){
        model.addAttribute("testRequestScope", "hello,Model");
        return "success";
    }

使用map

    @RequestMapping("/testRequestMap")
    public String testMap(Map<String, Object> map){
        map.put("testRequestScope", "hello,Map");
        return "success";
    }

使用ModelMap

    @RequestMapping("/testRequestModelMap")
    public String testModelMap(ModelMap modelMap){
        modelMap.addAttribute("testRequestScope", "hello,ModelMap");
        return "success";
    }

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 {}

向session域共享数据

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

向application域共享数据

    @RequestMapping("/testApplication")
    public String testApplication(HttpSession session){
		//获取最大域的对象
        ServletContext application = session.getServletContext();
        application.setAttribute("testApplicationScope", "hello,application");
        return "success";
    }

你可能感兴趣的:(SSM,java,spring,servlet)