jsp session的用法
session是使用bean的一个生存期限,一般为page,session意思是在这个用户没有离开网站之前一直有效,如果无法判断用户何时离开,一般依据系统设定,tomcat中设定为30分钟
<%@page import = "java.util.*" session="true"%>
<HTML>
<HEAD>
<TITLE>Using Sessions to Track Users</TITLE>
</HEAD><BODY>
<%
Integer counter = (Integer)session.getAttribute("counter");
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}session.setAttribute("counter", counter);
%>
<H1>Using Sessions to Track Users</H1>
Session ID: <%=session.getId()%>
<BR>
Session creation time: <%=new Date(session.getCreationTime())%>
<BR>
Last accessed time: <%=new Date(session.getLastAccessedTime())%>
<BR>
Number of times you've been here: <%=counter%>
</BODY>
</HTML>
获取或设置session值
<HTML>
<HEAD>
<TITLE>Using the Application Object</TITLE>
</HEAD><BODY>
<H1>Using the Application Object</H1>
<%
Integer counter = (Integer)session.getAttribute("counter");
String heading = null;
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}session.setAttribute("counter", counter);
Integer i = (Integer)application.getAttribute("i");
if (i == null) {
i = new Integer(1);
} else {
i = new Integer(i.intValue() + 1);
}application.setAttribute("i", i);
%>You have visited this page <%=counter%> times.
<BR>
This page has been visited by all users <%=i%> times.
</BODY>
</HTML>
我们的test.jsp教程 和test1.jsp都需要得到一个参数userdir,这个userdir是从数据库教程中得知,使用session将大大优化性能,程序如下:
设计一个javabean 存储userdir.
public class UserEnv {
private String userdir = "";
private String userurl = "";public UserEnv(){
//构建方法初始化userdir,可以从数据库中读取,这里简单给值ppp
userdir="pppp";
System.out.println("init userdir, one time");
}public String getUserdir() throws Exception{
return userdir;}
}
test1.jsp程序:
<%@ page contentType="text/html;charset=ISO8859_1" %>
<jsp:useBean id="myenv" scope="session" class="mysite.UserEnv"/>
<html>
<head>
<title>Untitled</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head><body>
this is test1.jsp:<%=myenv.getUserdir()%>
</body>
</html>
test2.jsp程序:
<%@ page contentType="text/html;charset=ISO8859_1" %><jsp:useBean id="myenv" scope="session" class="mysite.UserEnv"/>
<html>
<head>
<title>Untitled</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head><body>
this is test2.jsp:<%=myenv.getUserdir()%>
</body>
</html>
无论用户先调用test1.jsp还是test2.jsp, java bean UserEnv总是先初始化一次, 由于这个bean存在周期是seesion,因此该用户第二次以后只要在seesion有效期内再调用,myenv.getUserdir()将直接从bean内存中读取变量,不必再初始化.这样提高速度,又减少数据库访问量.
补充:Jsp教程,Jsp/Servlet开发工具