zoukankan      html  css  js  c++  java
  • JSP属性的四种保存范围(page request session application)

    JSP提供了四种属性的保存范围,分别为page、request、session、application

    其对应的类型分别为:PageContext、ServletRequest、HttpSession、ServletContext

    page范围:属性只在一个页面有效,页面跳转之后无效。

    可通过内置对象pageContext的setAttribute(name, value)方法设置属性,getAttribute(name)方法获取属性。

    pageContext是javax.servlet.jsp.PageContext抽象类类型

    <!-- 设置属性 -->
    <%
      pageContext.setAttribute("name", "leon");
    %>
    <!-- 获取属性 -->
    <%
      String str = (String) pageContext.getAttribute("name");
    %>

    request范围:属性在一个请求范围内有效,服务器跳转后<jsp:forword>有效,但客户端跳转后无效。

    可通过内置对象request的setAttribute(name, value)方法设置属性,getAttribute(name)方法获取属性

    request是javax.servlet.http.HttpServletRequest接口类型

    也可通过内置对象pageContext的setAttribute(name, value, scope)方法设置属性,setAttribute(name, value, scope)方法获取属性

    <!-- 设置属性 -->
    <%
      request.setAttribute("name", "James");
      pageContext.setAttribute("name", "james", pageContext.REQUEST_SCOPE)
    %>
    <!-- 获取属性 -->
    <%
      String str = (String) request.getAttribute("name");
      String str = (String) pageContext.getAttribute("name", pageContext.REQUEST_SCOPE())
    %>

    session范围:属性只在一个会话范围内有效,服务器跳转和客户端跳转都有效,但网页关闭重新打开后无效

    可通过内置对象session的setAttribute(name, value)方法设置属性,getAttribute(name)方法获取属性

    session是javax.servlet.http.HttpServletsession接口类型

    也可通过内置对象pageContext的setAttribute(name, value, scope)方法设置属性,getAttrubute(name, scope)方法获取属性

    <!-- 设置属性 -->
    <%
      session.setAttribute("name", "James");
      pageContext.setAttribute("name", "James", pageContext.SESSION_SCOPE)
    %>
    <!-- 获取属性 -->
    <%
      String str = (String) session.getAttribute("name");
      String str = (String) pageContext.getAttribute("name", pageContext.SESSION_SCOPE)
    %>

    application范围:属性在整个服务器上都有效,所有用户都可以使用,重启服务器后无效

    注意:如果设置过多的application属性范围会影响服务器的性能。

    可通过内置对象application的setAttribute(name, value)方法设置属性,getAttribute(name)方法获取属性

    application是javax.servlet.ServletContext接口类型

    也可通过内置对象pageContext.setAttribute(name, value, scope)方法设置属性,getAttribute(name, scope)方法获取属性

    <!-- 设置属性 -->
    <%
      application.setAttribute("name", "James");
      pageContext.setAttribute("name", "James", pageContext.APPLICATION_SCOPE)
    %>
    <!-- 获取属性 -->
    <%
      String str = (String) application.getAttribute("name");
      String str = (String) pageContext.getAttribute("name", pageContext.APPLICATION_SCOPE);
    %>

     移除属性

    可通过相应内置对象的removeAttribute(name)方法移除指定属性

    也可通过pageContext.removeAttribute(name, scope)方法移除指定属性

  • 相关阅读:
    Response.AddHeader使用实例收集
    JS回车键判断
    详解MongoDB中的多表关联查询($lookup)
    数据库设计三大范式
    一、表的设计步骤
    手把手教你,使用JWT实现单点登录
    【C#】ElasticSearch环境搭建与使用
    C#简单操作MongoDB
    net core WebAPI 初探及连接MySQL
    NoSQL 简介
  • 原文地址:https://www.cnblogs.com/0820LL/p/9842507.html
Copyright © 2011-2022 走看看