The correct understanding of HttpSession

Source: Internet
Author: User
Tags session id

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


It works like this:
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.

for session identification number (SessionID), There are two ways to achieve this: cookies and URL rewriting.

httpsession use
> Let's take a look at how the session is defined and manipulated in the API.
When you need to set up a session for the client, The servlet container creates a HttpSession object. It stores information related to this session. So, how many different users are connected in a servlet, how many httpsession objects are there.

2. Add or remove attributes from HttpSession;

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);



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

This interface defines two methods:
void Valuebound ( Httpsessionbindingevent e);
void Valueunbound ( Httpsessionbindingevent e);

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 basically a reason: The container has a session manager (such as Tomcat's Org.apache.catalina.session package inside the Class), providing the session's life cycle and persistent management and provide access to session data API;
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 there is no explicit expiration of the cookie, only in the browser's current process life time, can be removed 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. Note If the JSP is not displayed using <% @page session= "false"%> the session is closed, the JSP file will be automatically added to the servlet when it is translated to 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 Session 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 window access to the application will use 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.