JSP/Servlet: Servlet/JSP session tracking mechanism

Source: Internet
Author: User

1. Servlet session management mechanism

HTTP is designed as a stateless protocol. It means that the Web application does not know the information about the previous requests of the same user. One way to maintain session status information is to use the session tracking function provided by the Servlet or JSP Container. The Servlet API Specification defines a simple HttpSession interface, through which we can easily implement session tracking.

The HttpSession interface provides methods for storing and returning standard session attributes. Standard session attributes, such as session identifiers and application data, are saved as "name-value" pairs. In short, the HttpSession interface provides a standard method to save objects to the memory and extract these objects in the same user's subsequent requests. The method for saving data in a session is setAttribute (String s, Object o). The method for extracting the originally saved Object from the session is getAttribute (String s ).

In HTTP, there is no explicit termination signal when the user is no longer active. For this reason, we do not know whether the user has to return again. If we do not solve this problem in some way, a large number of HttpSession objects will be accumulated in the memory.

To this end, Servlet uses the "timeout limit" method to determine whether the user is still accessing: if a user does not send a subsequent request within a certain period of time, the user's session will be voided, the HttpSession object is released. The default session timeout interval is defined by the Servlet container. This value can be obtained through the getMaxInactiveInterval method and modified using the setMaxInactiveInterval method. The timeout time in these methods is measured in seconds. If the Session Timeout value is set to-1, the session never times out. Servlet can use the getLastAccessedTime method to obtain the last access time before the current request.

To obtain the HttpSession object, we can call the getSession method of the HttpServletRequest object. To correctly maintain the session status, we must call the getSession method before sending any response content.
User sessions can be voided manually or automatically. An expired session means that the HttpSession object and its data are deleted from the memory. For example, if a user no longer sends a request within a certain period of time (30 minutes by default), the Java Web Server will automatically invalidate his session.

The Servlet/JSP session tracking mechanism has certain limitations, such:

? Session objects are stored in the memory, occupying considerable resources.

? Session Tracing depends on cookies. For various reasons, especially for security reasons, some users disable cookies.

? Session tracing uses the session identifier created by the server. In multiple Web servers and multiple JVM environments, the Web server cannot identify the session identifiers created by other servers, and the session tracking mechanism cannot play a role.
To thoroughly understand the session tracing mechanism, we must first understand how sessions work in Servlet/JSP containers.

Ii. Session identifier

Each time a new user requests a JSP page that uses an HttpSession object, the JSP Container sends a special number to the browser in addition to sending back the response page. This special number is called a session identifier, which is a unique user identifier. After that, the HttpSession object will reside in the memory and wait for the same user to return its method again.

On the client, the browser saves the session identifier and sends it to the server in each subsequent request. The session identifier tells the JSP Container that the current request is not the first request sent by the user. The server has previously created an HttpSession object for this user. In this case, the JSP Container does not create a new HttpSession object for the user, but searches for an HttpSession object with the same session identifier, and then establishes the association between the HttpSession object and the current request.

The session identifier is transmitted between the server and the browser in the form of a Cookie. What if the browser does not support cookies? In this case, subsequent requests to the server do not contain session identifiers. As a result, the JSP Container considers the request to come from a new user and creates another HttpSession object. The previously created HttpSession object still resides in the memory, however, the user's previous session information is lost.

In addition, the Servlet/JSP Container only recognizes the session identifier it creates. If the same Web application runs on multiple servers of the Web farm, such a mechanism must exist: ensure that requests from the same user are always directed to the server that processes the user's first request.

Iii. Pseudo-session management mechanism

As mentioned above, Cookie-based session management technology faces various problems. Next we will design a new session management mechanism to solve these problems. This Session management mechanism is called the "Pseudo Session" mechanism, which has the following features:

? Objects and data are not stored in memory, but saved as text files. Each text file is associated with a specific user. The file name is the session identifier. Therefore, the file name must be unique.
? Text files are stored in a dedicated Directory, which can be accessed by all Web servers. Therefore, pseudo sessions can be used on Web farms.
? The session identifier is directly encoded into the URL instead of being sent as a Cookie. Therefore, the use of pseudo-session technology requires that all hyperlinks, including the ACTION attribute of HTML forms, be modified.
In addition, we need to consider the following points when implementing the pseudo-session management mechanism:
? It should be unrelated to the application. Other developers who want to implement the same function should be able to reuse it conveniently.
? For security reasons, there should be a way to generate random numbers for session identifiers.
? A timeout value should be set to invalidate expired sessions. If a user returns again after a certain period of time, the user will obtain a new session identifier. This prevents unauthorized users from using others' sessions.
? There should be a mechanism to collect expired sessions and delete the corresponding text files.
? If the user uses an expired session identifier to access the server again, even if the text file of the session identifier has not been deleted, the system should not allow the user to use the original session.
? At the same time, there should be a mechanism to update the last modification time of the session text file, so that the session is always up-to-date and valid when the user returns before the session expiration time.

Iv. Implement the pseudo-session management mechanism

The project described below is called the pseudo Session, which is a simple implementation of the pseudo session mechanism. Considering portability, we implement it in the form of JavaBean. The complete code of the pseudo sessionbean can be downloaded from the end of this article.

Pseudo sessionbean has the following fields ):
Public String path; public long timeOut;
Path is the directory that stores all session text files. If the number of Web servers is greater than one, this directory must be accessible to all servers. However, in order to prevent users from directly accessing these text files, this path should not allow users to access them directly. One way to solve this problem is to use directories outside the Web site root.

TimeOut is the time between the user's last request and the expiration time of the session. In the pseudo sessionbean code list, timeOut is set to 20 minutes in milliseconds, which is a reasonable timeOut value. If a user sends a request after the timeout period, the user will get a new session identifier.
Pseudo sessionbean has four methods: getSessionID, setValue, getValue, and deleteAllInvalidSessions.

4.1 getSessionID Method
The getSessionID method is declared as follows:
Public String getSessionID (HttpServletRequest request)
This method should be called at the beginning of each JSP page. It completes the following tasks:
? If this is the first access, a new session identifier is set for this user.
? Check the validity of the session identifier of the URL. If the session ID has expired, the getSessionID method returns a new session ID.
Let's take a look at the working process of the getSessionID method.
String sessionId = request. getParameter ("sessionId ");
ValidSessionIdFound is a tag used to indicate whether the session identifier is legal. The initial value of validSessionIdFound is false.
Boolean validSessionIdFound = false;
The now variable of the long type contains the server time when the request appears. This variable is used to determine the validity of a user session.
Long now = System. currentTimeMillis ();
If the session identifier is found, the getSessionID method checks its validity. The check process is as follows:
? A valid session identifier must have a text file of the same name.
? The last modification time and timeOut of the file must be later than the current time.
? If a text file corresponding to the session exists but the file has expired, the original file will be deleted.
? Change the last modification date of the text file corresponding to the legal session identifier to now.
These tasks are mainly completed by using the File object. The parameters for creating the File object are the path of the session text File:
If (sessionId! = Null ){
File f = new File (path + sessionId );
If (f. exists ()){
If (f. lastModified () + timeOut> now) {// The session is valid // when setLastModified is used, if the file has been locked by another program, // the program will not produce any exceptions, but the file data will not change f. setLastModified (now); validSessionIdFound = true;} else {// The session has expired // delete the file f. delete () ;}// end if (f. exists)} // end if (sessionId! = Null)
If there is no valid session identifier, the getSessionID method generates a session identifier and the corresponding text file:
If (! ValidSessionIdFound) {sessionId = Long. toString (now); // create a File f = new File (path + sessionId); try {f. createNewFile ();} catch (IOException & nbs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.