一、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>