四大作用域与传值

2019-12-13  本文已影响0人  Yanl__

1. 九大内置对象

名称 类型 含义 获取方式
request HttpSevletRequest 封装所有请求信息 方法参数
response HttpServletResponse 封装所有响应信息 方法参数
session HttpSession 封装所有会话信息 req.getSession()
application ServletContext 所有信息 getServletContext();</br>request.getServletContext();
out PrintWriter 输出对象 response.getWriter()
exception Exception 异常对象
page Object 当前页面对象
pageContext PageContext 获取其他对象
config ServletConfig 配置信息

2.四大作用域

  1. page
    1.1. 在当前页面不会重新实例化.
  2. request
    2.1 在一次请求中同一个对象,下次请求重新实例化一个request 对象.
  3. session
    3.1 一次会话.
    3.2 只要客户端Cookie 中传递的Jsessionid 不变,Session 不会重新实力会(不超过默认时间.)
    3.3 实际有效时间:
        3.3.1 浏览器关闭.Cookie 失效.
        3.3.2 默认时间.在时间范围内无任何交互.在tomcat 的web.xml 中配置
<session-config>
    <session-timeout>30</session-timeout>
</session-config>
  1. application
    4.1 只有在tomcat 启动项目时菜实例化.关闭tomcat 时销毁application

3.SpringMVC 作用域传值的四种方式

  1. 使用原生Servlet
    1.1 在HanlderMethod 参数中添加作用域对象
  2. 使用Map 集合
    2.1 把map 中内容放在request 作用域中
    2.2 spring 会对map 集合通过BindingAwareModelMap 进行实例
  3. 使用SpringMVC 中Model 接口
    3.1 把内容最终放入到request 作用域中.
  4. 使用SpringMVC 中ModelAndView 类
1.使用原生Servlet
@RequestMapping("demo1")
public String demo1(HttpServletRequest abc,HttpSession sessionParam){
    //request 作用域
    abc.setAttribute("req", "req 的值");
    //session 作用域
    HttpSession session = abc.getSession();
    session.setAttribute("session", "session 的值");
    sessionParam.setAttribute("sessionParam","sessionParam 的值");
    //appliaction 作用域
    ServletContext application =abc.getServletContext();
    application.setAttribute("application","application 的值");
    return "/index.jsp";
}

2.使用Map 集合
@RequestMapping("demo2")
public String demo2(Map<String,Object> map){
    System.out.println(map.getClass());
    map.put("map","map 的值");
    return "/index.jsp";
}

3.使用SpringMVC 中Model 接口
@RequestMapping("demo3")
public String demo3(Model model){
    model.addAttribute("model", "model 的值");
    return "/index.jsp";
}

4.使用SpringMVC 中ModelAndView 类
@RequestMapping("demo4")
public ModelAndView demo4(){
    //参数,跳转视图
    ModelAndView mav = new ModelAndView("/index.jsp");
    mav.addObject("mav", "mav 的值");
    return mav;
}

jsp中
request:${requestScope.req }
session:${sessionScope.session }
sessionParam:${sessionScope.sessionParam }
application:${applicationScope.application }
map:${requestScope.map }
model:${requestScope.model }
mav:${requestScope.mav }
上一篇下一篇

猜你喜欢

热点阅读