JSP内置对象的作用域

一、4个作用域

page

request

session:

application

都有setAttribute和getAttribute方法,cookie不是内置对象的范畴

二、四个作用域的区别

(1)作用域对应的内置对象

page作用域:

对应的内置对象pageContext

request作用域:

对应的内置对象是request

session作用域:

对应的内置对象是session

application作用域:

对应的内置对象是application

(2)作用域的对应范围

page作用域<request作用域<session作用域<application作用域

page只在当前页面有效

request在一次请求内有效

session在一次会话内有效

application对应整一个web应用

(3)例子解析作用域的对应范围:

i.page的作用域:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>page作用域的测试</title>
</head>
<body>
    <%
        pageContext.setAttribute("name","tom");
    %>
    <h3>333</h3>
    <%
        String name = (String) pageContext.getAttribute("name");
        out.write(name);
    %>
</body>
</html>

只在当前页面有效,在其他页面取不出来 

ii.request作用域:

request在一次请求内有效,重定向之后不是一个请求,所以如果是重定向就不会有数据

<body>
    <%
        request.setAttribute("name","jerry");
        request.getRequestDispatcher("target.jsp").forward(request,response);
    %>
</body>

tatget:

<%
   String name = (String) request.getAttribute("name");
%>
<%=name%>

iii.session作用域:

session在一次会话内有效,关闭浏览器再打开就是新的会话

session_test.jsp

<body>
    <%
        session.setAttribute("name","Tom and Jerry");
        response.sendRedirect("target.jsp");
    %>
</body>

tatget:

<%
    String session_name = (String) session.getAttribute("name");
%>
<%=session_name%>

iv.application作用域:

只要Tomcat服务器不关闭,重启浏览器或者在其他PC访问,Attribute的值都存在

<%
    application.setAttribute("name","hahaha");
    response.sendRedirect("target.jsp");
  %>

tatget:

<%
   String name = (String) application.getAttribute("name");
%>
<%=name%>

实验:网站访问量的统计

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        Integer count = (Integer) application.getAttribute("count");
        if(count == null){
            count = 0;
            application.setAttribute("count",count);
        }else{
            count++;
            application.setAttribute("count",count);
        }

    %>
    你是当前第<%=count%>位访问
</body>
</html>

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值