Introduction to TOMCAT6 session creation mechanism

Source: Internet
Author: User
Tags session id sessions
background:
The test department does the stress test, the result did not pressure how long, appears outofmemory.
Reason lookup, through monitoring tools, found standardsession(Org.apache.catalina.session. standardsessionObjects are growing, and there is no doubt that the session object is constantly being created.
Note: Generally do stress tests, each request will not specify the Jessesionid value, resulting in the Web container that each request is a new request, and then create the session object.
The colleague is responsible for the code review and discovers that the application does not have any place to hold the session content. Confused ...

question: When does the Tomcat container create a Session object?
Take it for granted that the session object is created only when it is dynamically stored. But is that really the case?

First look at the servlet protocol description:
Please see:
GetSession (Boolean Create) Method:
Javax.servlet.http.HttpServletRequest.getSession (Boolean Create)
Returns the current HttpSession associated with this request or, if if there are no current sessions and create is true, ret Urns a new session.

IF Create is false with the request has no valid HttpSession, this method returns NULL.

To make sure the sessions is properly maintained, and you are must call this method before the response is committed.

Simply put: When the Create variable is true, if the current session does not exist, a new session is created and returned.

GetSession () Method:
Javax.servlet.http. HttpSession getsession ();
Returns the associated with this request, or if the request is does not have a, creates one.
Simply put: When the current session does not exist, create and return.


Therefore, the Protocol stipulates that the session object is created when the GetSession method is invoked.



Now that the agreement is fixed, let's look at how Tomcat is implemented: (The following description is based on the Tomcat6.0.14 version of the source code)
Let's look at a simple class diagram:


ApplicationContext: implementation of ServletContext in the servlet specification
Standardcontext: The context default implementation of Tomcat definition. Maintains a copy of the SessionManager object and manages the session object. All session objects are stored in the manager-defined map<string,session> container .
Stanardmanager: Standard session management, storing session in content, Web container closing, persisting to local file
Persistentmanager: Persistent implementation of Session management, by default, there are two ways to implement:
--Persisted to local file
--Persisted to the database

After understanding the approximate concept, look back and see Org.apache.catalina.connector. RequestHow GetSession () is implemented.
The final call is the Dogetsession (Boolean Create) method, see:
Protected session Dogetsession (Boolean create) {

There cannot be a sessions if no context has been assigned yet
if (context = null)
return (NULL);

Return the "session if it exists" and is valid
if (session!= null) &&! session.isvalid ())
session = NULL;
if (session!= NULL)
return (session);

Return the requested sessions if it exists and is valid
Manager manager = NULL;
If (context!= null)
Manager = Context.getmanager ();
if (manager = = null)
return (NULL); Sessions are not supported
if (Requestedsessionid!= null) {
try {
Session = Manager.findsession (Requestedsessionid);
catch (IOException e) {
session = NULL;
}
if (session!= null) &&! session.isvalid ())
session = NULL;
if (session!= null) {
Session.access ();
return (session);
}
}

Create a new session if requested and the response are not committed
if (! Create)
return (NULL);
If (context!= null) && (response!= null) &&
Context.getcookies () &&
Response.getresponse (). iscommitted ()) {
throw new IllegalStateException
(Sm.getstring ("coyoterequest.sessioncreatecommitted"));
}

Attempt to reuse session ID if one is submitted in a cookie
Don't reuse the session ID if it's from URL, to prevent possible
Phishing attacks
if (Connector.getemptysessionpath ()
&& Isrequestedsessionidfromcookie ()) {
Session = Manager.createsession (Getrequestedsessionid ());
} else {
session = Manager.createsession (null);
}

Creating a new session cookie based in that session
if (session!= null) && (getcontext ()!= null)
&& GetContext (). GetCookies ()) {
Cookie cookie = new Cookie (globals.session_cookie_name,
Session.getidinternal ());
Configuresessioncookie (cookie);
Response.addcookieinternal (Cookie, context.getusehttponly ());
}

if (session!= null) {
Session.access ();
return (session);
} else {
return (NULL);
}

}

At this point, a simple description of the Tomcat session to create the mechanism, interested students to in-depth understanding, you may wish to look at the Tomcat source implementation.



Add a note, incidentally, by mentioning the expiration policy of the session.
The Expiration method is:
Org.apache.catalina.session. Managerbase(Standardmanager base Class) Processexpires method:
public void Processexpires () {

Long TimeNow = System.currenttimemillis ();
Session sessions[] = Findsessions ();
int expirehere = 0;

if (log.isdebugenabled ())
Log.debug ("Start expire Sessions" + getName () + "at" + TimeNow + "Sessioncount" + Sessions.leng TH);
for (int i = 0; i < sessions.length i + +) {
if (Sessions[i]!= null &&! sessions[i].isvalid ()) {
Expirehere + +;
}
}
Long timeend = System.currenttimemillis ();
if (log.isdebugenabled ())
Log.debug ("End expire Sessions" + getName () + "Processingtime" + (Timeend-timenow) + "Expired SE Ssions: "+ expirehere);
Processingtime + = (timeend-timenow);

}
Among them, the Session.isvalid () method will do the session cleanup work.


In Org.apache.catalina.core.ContainerBase, a background thread is started, running some background tasks, and the session expiration task is one of them:
protected void ThreadStart () {

if (thread!= null)
return;
if (backgroundprocessordelay <= 0)
return;

Threaddone = false;
String threadname = "containerbackgroundprocessor[" + toString () + "]";
thread = new Thread (new Containerbackgroundprocessor (), threadname);
Thread.setdaemon (TRUE);
Thread.Start ();

}

To be precise, unless your application does not need to be saved at all (stateless), otherwise, as long as there is a new connection, the Web container needs to create a session concept to maintain state information.
But what is the session? Session is only a concept: "Provides a way to identify a user across more than one page request or visit to a Web site and to store in Formation about that user. " --Simply, save the user state information.
Therefore, we can completely according to the needs of the application, custom session implementation:
A. Session saved to JVM content--tomcat default implementation
B. Session save to Cookie--cookie-based session
C. session save to local file--tomcat one of the Non-default implementations provided
D. Session save in cache store-for example, common memcached
E. session is saved to the database-for example, to the MySQL database session table, with the active session cached in the middle for cached.
......
Then, if an application has a large number of one-time requests from different users (just a one-off, such as the scenario described in the above article), then choosing a c,d,e solution can effectively solve the problem described in the article.

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.