The JSP session is a life cycle of bean. Generally, it is page, which means that the session is valid until the user leaves the website. If the user cannot determine when to leave, it is generally set based on the system, tomcat is set to 30 minutes.
We use the seesion function to allow multiple JSP programs to operate on the same Java Bean, so this Java Bean can be used as our "global variable pool" in the traditional sense ". (in java, we can use static to statically convert a variable and method, and use Singleton to uniquely convert the object .)
In project practice, many parameters in our JSP program need to be read from the database. Some parameters can be read once actually. If it is designed that each user needs to read the database every time a page is generated, obviously, the database load is huge and time-consuming. Although database connection pool optimization may occur, it is our programming principle to use the database as little as possible.
For example, both test. jsp and test1.jsp need to get a parameter userdir, Which is learned from the database. Using session will greatly optimize the performance. The program is as follows:
Design a JavaBean storage userdir.
Public class userenv {
Private string userdir = "";
Private string userurl = "";
Public userenv (){
// The construction method initializes userdir, which can be read from the database. Here, the value is PPP.
Userdir = "PPPP ";
System. Out. println ("init userdir, one time ");
}
Public String getuserdir () throws exception {
Return userdir;
}
}
Test1.jsp program:
<% @ 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 program:
<% @ 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>
No matter whether you call test1.jsp or test2.jsp first, Java Bean userenv is always initialized first. Because the bean has a seesion cycle, this user only needs to call it within the seesion validity period after the second time, myenv. getuserdir () will read the variable directly from the bean memory without initialization. this increases the speed and reduces the database access volume.
In this way, we have a way to share variables or methods between JSP programs.