The correct understanding of HttpSession

Source: Internet
Author: User
Tags session id rfc sessions

The misunderstanding about HttpSession is too much, it is a very simple question, how can it be so complicated? Let me say what I understand:

A session is a series of communication between a user and a server. The server has the ability to distinguish between different users. A session is established from a user to the server to start the first request, and the user explicitly end or session timeout for the end.
Here's how it works:
1. When a user sends the first request to the server, the server establishes a session for it and creates an identification number for the session;
2. All subsequent requests by this user should include this identification number. The server will proofread the identification number to determine which session the request belongs to.
This mechanism does not use IP as the identity, because many machines are online through a proxy server, unable to distinguish each machine.
There are two ways to implement the session identification number (SessionID): Cookies and URL rewriting.

Use of HttpSession
Let's take a look at how the session is defined and manipulated in the API.
The servlet container creates a HttpSession object when it is necessary to establish a session for the client. It stores information related to this session. So, how many different users are connected in a servlet, how many httpsession objects are there.
The mechanism used is:
1. Extract the HttpSession object from the request;
2. Add or remove attributes from the httpsession;
3. Turn off or invalidate the httpsession as needed.

There are two overloaded methods in the request to get a HttpSession object.
HttpSession getsession (Boolean Create)/getsession (); The function is to extract the HttpSession object if it is not created automatically.

Once we get to the HttpSession object, we need to use some methods of httpsession to set and change some parameters. Such as:
void SetAttribute (String name, Object value);
Object getattribute (String name);
void RemoveAttribute (String name);

A total of four session listener interfaces and two session events associated with them are defined in the Javax.servlet.http package. respectively:
Httpsessionattributelistener and Httpsessionbindingevent;
Httpsessionbindinglistener and Httpsessionbindingevent;
Httpsessionlistener and Httpsessionevent;
Httpsessionactivationlistener and Httpsessionevent.

Their inheritance relationship is:
The parent class of all four interfaces is java.util.EventListener;
Httpsessionevent extended java.util.EventObject;
and Httpsessionbindingevent expanded the httpsessionevent.

The following are detailed separately:
Httpsessionattributelistener
When the properties in session are added, changed, and are notified when deleted. This interface has been mentioned in the previous section, the main look at the other three.

Httpsessionbindinglistener
When a class that implements the Httpsessionbindinglistener is added to the httpsession (or removed from it), a httpbindingevent event is generated, and these events are received by itself.
This interface defines two methods:
void Valuebound (Httpsessionbindingevent e);
void Valueunbound (Httpsessionbindingevent e);
When more than one class that implements Httpsessionbindinglistener is added to the HttpSession, the various methods are only interested in this class and will not ignore the addition of other classes.
Even among the different instances of the same class, they are not concerned with each other (snow in front of each sweep).

We can see that the first two interfaces react to the Httpsessionbindingevent event, but the mechanism is different.
Httpsessionattributelistener is registered in Web. XML, the servlet container creates only one instance for any Servlet service that adds properties to the session. The object that triggers the event is all instances that can be converted to object.
Httpsessionbindinglistener does not have to be registered in Web. XML, creates an instance with new in each servlet, and is only interested in adding (or removing) This instance to the session. The object that triggered the event is just itself.

Httpsessionlistener
Interested in creating and canceling the session. Need to be registered in Web. Xml.
A total of two methods:
void sessioncreated (httpsessionevent se);
void sessiondestroyed (httpsessionevent se);
With it we can easily create a class to count the session.
Perhaps we would simply consider using the Sessiondestroyed method to do some cleanup at the end of the session. However, please note that when this method is called, the session is over and you cannot extract any information from it. So we have to go a few ways.
One commonly used method is to use the Httpsessionbindinglistener interface. Add a property to the session creation, and the last thing before the end of the session is to delete the property, which will trigger the Valueunbound method, and all cleanup of the session can be done in this method.

Httpsessionactivationlistener
When the session spans the JVM in a distributed environment, objects that implement the interface are notified. A total of two methods:
void Sessiondidactivate (httpsessionevent se);
void Sessionwillpassivate (httpsessionevent se);


1, the HTTP protocol itself is a "connection-request-answer-close connection" mode, is a stateless protocol (HTTP is only a transport protocol);
2, the cookie specification is in order to add status tracking for HTTP (if you want to accurately grasp, it is recommended to carefully read the relevant RFC), but not the only means;
3, the so-called session, refers to the client and the service side of the interaction between the process of state information (data); how this state is defined, how long the life period, this is the application itself things;
4, because the B/s calculation model is completed on the server side, the client has only simple display logic, so the session data should be transparent to the client is not understandable and should be controlled by the service side; The session data is either saved to the service side (HttpSession), Either pass between the client and the server (cookie or URL rewritting or hidden input);
5, because of the stateless nature of the HTTP itself, the server can not know that the client has sent the request is from a customer, so when using the server HttpSession storage session data, each client request should contain a session of the identity (SID, Jsessionid, etc.) to tell the server;
6. The advantage of saving session data on the server (such as httpsession) is to reduce the length of the HTTP request and improve the network transmission efficiency; The client session Information store is the opposite;
7, the client session storage only one way: the cookie (URL rewritting and hidden input because cannot be persisted, does not count, only as the Exchange session ID, namely a method of session tracking , and the service-side approach is roughly the same: the container has a session manager (such as the class inside Tomcat's Org.apache.catalina.session package) that provides the session lifecycle and persistence management and provides an API to access session data;
8, using the server or client session storage to see the actual situation of the application. In general, users are not required to sign in to the public service system (such as Google) to use cookies for client session storage (such as Google's user preferences), while the user-managed system uses server-side storage. The reason is obvious: No user login system can only identify users of the user's computer, for a machine do not know who is who, server session storage is no use, and the user management system can be used to manage the user's personal data, so as to provide arbitrary complex personalized services;
9, the client and server session storage in performance, security, cross-site capabilities, programming convenience and other aspects have a certain difference, and the pros and cons are not absolute (for example, Theserverside claims not to use httpsession, so the performance is good, This is obvious: a system with hundreds of millions of access users, to retrieve the user's preference information in the server database is obviously inefficient, the session manager no matter what data structure and algorithm are consuming a lot of memory and CPU time, and using cookies, Do not have to retrieve and maintain session data at all, the server can be made stateless, of course, efficient);
10.The so-called "session cookie" simply means that a cookie that does not explicitly indicate the expiration date is valid only for the lifetime of the browser's current process and can be purged by subsequent set-cookie operations. When a program needs to create a session for a client's request, the server first checks to see if a session ID is included in the client's request-called the session ID. If it contains a session The ID indicates that the session was previously created for this client, and the server retrieves the session using the session ID (if it is not retrieved, it may create a new one) if the client request does not include the session ID. Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, this session The ID will be returned to the client in this response to be saved. This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid.1, when the session was created
A common misconception is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, and note that if the JSP does not display the use <% @page session= "false"%> the session is closed, the JSP file is automatically translated into a servlet with such a statement HttpSession session = Httpservletrequest.getsession (true); This is also the origin of the hidden session object in JSP. Because the session consumes memory resources, if you do not intend to use the session, you should close it in all JSPs.
2. Must the object stored in the session be serializable?
are not required. Requires that the object be serializable only for the session to be replicated in the cluster or to be persisted or, if necessary, the server can swap the session out of memory temporarily. 3, how to properly deal with the possibility of the client to prohibit cookies
Use URL overrides for all URLs, including hyperlinks, action for form, and redirected URLs, as described in the following example:
http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770Instead, use the Httpservletresponse.encodeurl () method, for Example:out.println ("<a href=/" "+ Response.encodeurl ( "myshop/catalog.jsp") + "/" >catalog</a> ");
Calling the Encodeurl () method determines if the URL needs to is rewritten, and if so, it rewrites it by including the SES Sion ID in the URL. The session ID is appended to the URL and begins with a semicolon.
In addition to URLs that is returned as a response to WebLogic Server, also encode URLs that send redirects. For example:
if (Session.isnew ()) Response.sendredirect (Response.encoderedirecturl (Welcomeurl)); 4, Open two browser windows access the application using the same session or a different session
Refer to the third section of the discussion of the cookie, for the session is to identify the ID, so different browsers, different window opening and different ways of storing cookies will have an impact on the answer to this question. The misunderstanding about HttpSession is too much, it is a very simple question, how can it be so complicated? Let me say what I understand:

A session is a series of communication between a user and a server. The server has the ability to distinguish between different users. A session is established from a user to the server to start the first request, and the user explicitly end or session timeout for the end.
Here's how it works:
1. When a user sends the first request to the server, the server establishes a session for it and creates an identification number for the session;
2. All subsequent requests by this user should include this identification number. The server will proofread the identification number to determine which session the request belongs to.
This mechanism does not use IP as the identity, because many machines are online through a proxy server, unable to distinguish each machine.
There are two ways to implement the session identification number (SessionID): Cookies and URL rewriting.

Use of HttpSession
Let's take a look at how the session is defined and manipulated in the API.
The servlet container creates a HttpSession object when it is necessary to establish a session for the client. It stores information related to this session. So, how many different users are connected in a servlet, how many httpsession objects are there.
The mechanism used is:
1. Extract the HttpSession object from the request;
2. Add or remove attributes from the httpsession;
3. Turn off or invalidate the httpsession as needed.

There are two overloaded methods in the request to get a HttpSession object.
HttpSession getsession (Boolean Create)/getsession (); The function is to extract the HttpSession object if it is not created automatically.

Once we get to the HttpSession object, we need to use some methods of httpsession to set and change some parameters. Such as:
void SetAttribute (String name, Object value);
Object getattribute (String name);
void RemoveAttribute (String name);

A total of four session listener interfaces and two session events associated with them are defined in the Javax.servlet.http package. respectively:
Httpsessionattributelistener and Httpsessionbindingevent;
Httpsessionbindinglistener and Httpsessionbindingevent;
Httpsessionlistener and Httpsessionevent;
Httpsessionactivationlistener and Httpsessionevent.

Their inheritance relationship is:
The parent class of all four interfaces is java.util.EventListener;
Httpsessionevent extended java.util.EventObject;
and Httpsessionbindingevent expanded the httpsessionevent.

The following are detailed separately:
Httpsessionattributelistener
When the properties in session are added, changed, and are notified when deleted. This interface has been mentioned in the previous section, the main look at the other three.

Httpsessionbindinglistener
When a class that implements the Httpsessionbindinglistener is added to the httpsession (or removed from it), a httpbindingevent event is generated, and these events are received by itself.
This interface defines two methods:
void Valuebound (Httpsessionbindingevent e);
void Valueunbound (Httpsessionbindingevent e);
When more than one class that implements Httpsessionbindinglistener is added to the HttpSession, the various methods are only interested in this class and will not ignore the addition of other classes.
Even among the different instances of the same class, they are not concerned with each other (snow in front of each sweep).

We can see that the first two interfaces react to the Httpsessionbindingevent event, but the mechanism is different.
Httpsessionattributelistener is registered in Web. XML, the servlet container creates only one instance for any Servlet service that adds properties to the session. The object that triggers the event is all instances that can be converted to object.
Httpsessionbindinglistener does not have to be registered in Web. XML, creates an instance with new in each servlet, and is only interested in adding (or removing) This instance to the session. The object that triggered the event is just itself.

Httpsessionlistener
Interested in creating and canceling the session. Need to be registered in Web. Xml.
A total of two methods:
void sessioncreated (httpsessionevent se);
void sessiondestroyed (httpsessionevent se);
With it we can easily create a class to count the session.
Perhaps we would simply consider using the Sessiondestroyed method to do some cleanup at the end of the session. However, please note that when this method is called, the session is over and you cannot extract any information from it. So we have to go a few ways.
One commonly used method is to use the Httpsessionbindinglistener interface. Add a property to the session creation, and the last thing before the end of the session is to delete the property, which will trigger the Valueunbound method, and all cleanup of the session can be done in this method.

Httpsessionactivationlistener
When the session spans the JVM in a distributed environment, objects that implement the interface are notified. A total of two methods:
void Sessiondidactivate (httpsessionevent se);
void Sessionwillpassivate (httpsessionevent se);


1, the HTTP protocol itself is a "connection-request-answer-close connection" mode, is a stateless protocol (HTTP is only a transport protocol);
2, the cookie specification is in order to add status tracking for HTTP (if you want to accurately grasp, it is recommended to carefully read the relevant RFC), but not the only means;
3, the so-called session, refers to the client and the service side of the interaction between the process of state information (data); how this state is defined, how long the life period, this is the application itself things;
4, because the B/s calculation model is completed on the server side, the client has only simple display logic, so the session data should be transparent to the client is not understandable and should be controlled by the service side; The session data is either saved to the service side (HttpSession), Either pass between the client and the server (cookie or URL rewritting or hidden input);
5, because of the stateless nature of the HTTP itself, the server can not know that the client has sent the request is from a customer, so when using the server HttpSession storage session data, each client request should contain a session of the identity (SID, Jsessionid, etc.) to tell the server;
6. The advantage of saving session data on the server (such as httpsession) is to reduce the length of the HTTP request and improve the network transmission efficiency; The client session Information store is the opposite;
7, the client session storage only one way: the cookie (URL rewritting and hidden input because cannot be persisted, does not count, only as the Exchange session ID, namely a method of session tracking , and the service-side approach is roughly the same: the container has a session manager (such as the class inside Tomcat's Org.apache.catalina.session package) that provides the session lifecycle and persistence management and provides an API to access session data;
8, using the server or client session storage to see the actual situation of the application. In general, users are not required to sign in to the public service system (such as Google) to use cookies for client session storage (such as Google's user preferences), while the user-managed system uses server-side storage. The reason is obvious: No user login system can only identify users of the user's computer, for a machine do not know who is who, server session storage is no use, and the user management system can be used to manage the user's personal data, so as to provide arbitrary complex personalized services;
9, the client and server session storage in performance, security, cross-site capabilities, programming convenience and other aspects have a certain difference, and the pros and cons are not absolute (for example, Theserverside claims not to use httpsession, so the performance is good, This is obvious: a system with hundreds of millions of access users, to retrieve the user's preference information in the server database is obviously inefficient, the session manager no matter what data structure and algorithm are consuming a lot of memory and CPU time, and using cookies, Do not have to retrieve and maintain session data at all, the server can be made stateless, of course, efficient);
10.The so-called "session cookie" simply means that a cookie that does not explicitly indicate the expiration date is valid only for the lifetime of the browser's current process and can be purged by subsequent set-cookie operations. When a program needs to create a session for a client's request, the server first checks to see if a session ID is included in the client's request-called the session ID. If it contains a session The ID indicates that the session was previously created for this client, and the server retrieves the session using the session ID (if it is not retrieved, it may create a new one) if the client request does not include the session ID. Creates a session for this client and generates a session Id,session ID value associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, this session The ID will be returned to the client in this response to be saved. This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid.1, when the session was created
A common misconception is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, and note that if the JSP does not display the use <% @page session= "false"%> the session is closed, the JSP file is automatically translated into a servlet with such a statement HttpSession session = Httpservletrequest.getsession (true); This is also the origin of the hidden session object in JSP. Because the session consumes memory resources, if you do not intend to use the session, you should close it in all JSPs.
2. Must the object stored in the session be serializable?
are not required. Requires that the object be serializable only for the session to be replicated in the cluster or to be persisted or, if necessary, the server can swap the session out of memory temporarily. 3, how to properly deal with the possibility of the client to prohibit cookies
Use URL overrides for all URLs, including hyperlinks, action for form, and redirected URLs, as described in the following example:
http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770Instead, use the Httpservletresponse.encodeurl () method, for Example:out.println ("<a href=/" "+ Response.encodeurl ( "myshop/catalog.jsp") + "/" >catalog</a> ");
Calling the Encodeurl () method determines if the URL needs to is rewritten, and if so, it rewrites it by including the SES Sion ID in the URL. The session ID is appended to the URL and begins with a semicolon.
In addition to URLs that is returned as a response to WebLogic Server, also encode URLs that send redirects. For example:
if (Session.isnew ()) Response.sendredirect (Response.encoderedirecturl (Welcomeurl)); 4, Open two browser windows access the application using the same session or a different session
Refer to the third section of the discussion of the cookie, for the session is to identify the ID, so different browsers, different window opening and different ways of storing cookies will have an impact on the answer to this question.

The correct understanding of HttpSession

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.