前段时间我的理解不是很充分,经过导师的指点后,我重新整理了此篇:
Session域(session)周期:会话结束,浏览器进程,只要当前页面没有关闭(没有被程序强制清除),不管怎么跳转都有效。Session里的变量一直在累加,只要关闭浏览器,再次重启浏览器访问这页,session里的变量就重新计算。若把变量放到session里,就说明它的作用域是session,它的有效范围是当前会话。所谓当前会话就是指从用户打开浏览器开始,到该用户关闭浏览器这中间的过程。这个过程可能包含多个请求响应。换句话说,只要用户不关浏览器,服务器就有办法知道这些请求是同一个用户发起的,这整个的过程称为一个会话(session),而放到会话中的变量,就可以在当前会话的所有请求中使用。
Application域(servletContext)周期:整个web应用,只要服务器没有重启(没有被程序强制清除),数据就有效。Application里的变量一直在累加,除非你重启tomcat否则它会一直变大。如果把变量放到application中,就说明它的作用域是application,它的有效范围是整个应用。整个应用是指,从应用启动,到应用结束。注意我们并没说“服务器启动,到服务器关闭”,这是因为一个服务器可能部署多个应用,当然若你关闭了服务器,就会把上面的所有应用都关闭了。Application 作用域的变量,他们的存活时间是最长的,如果不进行手工删除,他们就一直可以使用。Application里的变量可以被所有用户共用。如果用户甲的操作修改了application中的变量,用户乙访问时得到的是修改后的值。这在其他scope中都是不会发生的,page,request,session都是完全隔离的,无论如何修改都不会影响其他数据。
请看例子:
Application--->blog.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'blog.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
//2.取值
Integer count =(Integer)application.getAttribute("count");
//3.
if(count!=null){
count++;
application.setAttribute("count", count);
}else{
count =1;
//1.存入到
application.setAttribute("count",count);
}
%>
阅读<%=count %>次数
This is my JSP page. <br>
</body>
</html>
Session->blog1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'blog.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
//2.取值
Integer count =(Integer)session.getAttribute("count");
//3.
if(count!=null){
count++;
session.setAttribute("count", count);
}else{
count =1;
//1.存入到
session.setAttribute("count",count);
}
%>
阅读<%=count %>次数
This is my JSP page. <br>
</body>
</html>