zoukankan      html  css  js  c++  java
  • JSP九大内置对象及四个作用域

    JSP九大内置对象及四大作用域概述

    Jsp九大内置对象及四大作用域概述:

      Jsp开发中,Jsp提供了9个内置对象,这些内置对象将由容器为用户进行实例化,用户直接使用即可。这9个内置对象是:pageContext、request、session,application、config,out,page,exception;常用的是前面5个,需要熟练掌握;

    Jsp开发中,可以保存数据,jsp提供了四种数据保存范围;分别是page, request, session, application;

    Jsp四大作用域:

    Page范围:只在一个页面中保存数据;javax.servlet.jsp.PageContext(抽象类)

    <%

    //内置对象pagecontext key--->value
    pageContext.setAttribute("name", "page王二小");
    pageContext.setAttribute("age", 18);
    %>
    <%
    String name=(String)pageContext.getAttribute("name");
    int age= (Integer)pageContext.getAttribute("age");
    %>
    <font>姓名:<%=name %></font></br>
    <font>年龄:<%=age %></font></br>

    Request范围:只在一个请求中保存数据;javax.servlet.http.HttpServletRequest(接口)

    requestContext.jsp

    代码:  

    <%
    //内置对象requestcontext key--->value
    request.setAttribute("name", "request王二小");
    request.setAttribute("age",18);
    %>
    <jsp:forward page="requestTarget.jsp" />

    requestTarget.jsp:

    <%

    String name=(String)request.getAttribute("name");
    int age=(Integer)request.getAttribute("age");
    %>
    <font>name:<%=name %></font></br>
    <font>age:<%=age %></font>

    Session范围:在一次会话范围中保存数据(保存在服务器里面,默认是半个小时),仅存单个用户使用;javax.servlet.http.HttpSession(接口)

     sessionContext.jsp:  

    <%
    //内置对象sessionContext key--->value
    session.setAttribute("name", "session王二小");
    session.setAttribute("age",18);
    %>
    <h1>session值设置完毕</h1>

     sessionTarget.jsp:

    <%
    String name=(String)session.getAttribute("name");
    int age=(Integer)session.getAttribute("age");
    %>
    <font>名字:<%=name%></font>
    <font>年龄:<%=age %></font>

    Application范围:在整个服务器上保存数据,所用用户共享;javax.servlet.ServletContext(接口)

    applicationScope.jsp:

    <%
    application.setAttribute("name", "application王二小");
    application.setAttribute("age",18);
    %>
    <h1>application设置完成</h1>

    applicationTarget.jsp: 

    <%
    String name=(String)application.getAttribute("name");
    int age=(Integer)application.getAttribute("age");
    %>
    <font>名字:<%=name%></font><br/>
    <font>年龄:<%=age %></font>

    关于request:

    如果要取到发送请求的信息。我们可以使用下面的代码:(在jsp里面导入包:<%@page import="java.util.*" %>   )

    <%

    Enumeration enu=request.getHeaderNames();
    while(enu.hasMoreElements()){
    String headerName=(String)enu.nextElement();
    String headerValue=request.getHeader(headerName);
    %>
    <h4><%=headerName %>&nbsp;<%=headerValue %></h4>
    <%
    }
    %>

    运行结果如图所示:

     

  • 相关阅读:
    Codeforces461E Appleman and a Game 做题心得
    关于贪心问题的处理
    各种容斥 笔记
    博弈论 笔记
    家庭多个路由器组网方案(AP+AC)
    21.06.06 训练赛
    Redirect...
    Web Api实践系列(三)route特性使用
    《Red Tuner》隐私政策
    前缀和-1915. 最美子字符串的数目
  • 原文地址:https://www.cnblogs.com/zyxsblogs/p/9572152.html
Copyright © 2011-2022 走看看