In-depth explanation of sessions and explanation of sessions

Source: Internet
Author: User

In-depth explanation of sessions and explanation of sessions
Original works of Lin bingwen Evankaka. Reprinted please indicate the source http://blog.csdn.net/evankaka

Abstract: Although the session mechanism has been adopted in web applications for a long time, many people still do not know the nature of the session mechanism, and even cannot correctly apply this technology. This article will discuss in detail the working mechanism of the session and answer frequently asked questions about the application of the session mechanism in Java web applications.

Directory:
I. Term session
Ii. HTTP protocol and status maintenance
3. Understanding cookie Mechanism
4. Understanding the session mechanism
5. Understand javax. servlet. http. HttpSession
Vi. HttpSession FAQs
7. Cross-Application session sharing
VIII. Summary


I. Term session


Session, which is often translated into sessions in Chinese. Its original meaning refers to a series of actions/messages that start and end, for example, a series of processes from picking up a phone call and dialing to hanging up a phone call can be called a session. Sometimes we can see this: "during a browser session ,... the term "session" here uses its original meaning, which refers to the period from opening a browser window to closing it. The most confusing is the phrase "a user (client) is in a session", which may refer to a series of actions of the user (generally a series of actions related to a specific purpose, for example, an online shopping process, from login to purchase of goods to checkout and logout, is sometimes called a transaction. However, sometimes it may only refer to a connection or a meaning, the differences can only be inferred by context.

However, when a session is associated with a network protocol, it often implies two meanings: "connection-oriented" and "/" persistence, "connection orientation" refers to the establishment of a communication channel before the communication parties establish a communication channel, such as a phone call, until the other party receives a telephone communication. In contrast, it refers to writing a letter, when you send a letter, you cannot confirm whether the address of the other party is correct. The communication channel may not be established, but for the sender, the communication has started. "Keep status" means that the communication party can associate a series of messages so that messages can be mutually dependent, for example, a waiter can recognize an old customer who has visited the store again and remembers that the customer still owes a dollar to the store. Such examples include "One TCP session" or "one POP3 session ".

In the era of vigorous development of web servers, session semantics in the context of web development has been expanded, it refers to a kind of solution that maintains the status between the client and the server. Sometimes session refers to the storage structure of this solution, such as "Saving xxx in session ". Various languages used for web development provide support for this solution to a certain extent. Therefore, in a specific language context, session is also used to refer to the solution of this language, for example, the javax. servlet. http. httpSession is short for session.

As this confusion cannot be changed, the use of session in this article will also have different meanings according to the context.
In this article, we use the Chinese "browser session period" to express the meaning, the "session mechanism" to express the meaning, the "session" to express the meaning, and the specific "HttpSession" to express the meaning.

2. HTTP and State-preserving HTTP are stateless. That is to say, when a customer accesses the server, the server does not retain any information of the client. Therefore, the Web server treats each access from the same customer as a new access. But sometimes the server needs to retain the client information to identify multiple accesses from the same customer. How can this problem be achieved? To track the user's operation status, the Servlet container uses an object called HttpSession to implement this function, which is called session mechanism. A Session is a series of interactions between a customer and the Web server over a period of time. During a Session, the customer may access the same page multiple times, it is also possible to access multiple server resources.
HTTP is a stateless communication protocol. When a client sends a request, the server establishes a connection. Once the request ends, the server terminates the connection. this mechanism makes it impossible for the server to determine whether the client currently being connected is the same customer as a previous connection. In some cases, you must try to maintain the customer status on the server. This technology is called session tracking. session tracking can be implemented in the following four ways: -Cookie object: Client Session -Use the request object (ServletRequest or HttpServletRequest) -Use Session Object (HttpSession) -Use the context object (ServletContext)3. Understanding the basic principles of the cookie mechanism is as simple as the above example, but there are still several problems to solve: how to distribute "membership cards" and the content of "membership cards; and how the customer uses the "membership card ".

The orthodox cookie distribution is implemented by extending the HTTP protocol. The server prompts the browser to generate the corresponding cookie by adding a special line in the HTTP response header. However, pure client scripts such as JavaScript or VBScript can also generate cookies.

Cookies are automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. If the declared range of a cookie is greater than or equal to the location where the requested resource is located, the cookie is attached to the HTTP request header of the requested resource and sent to the server. This means that the McDonald's membership card can only be presented in the McDonald's store. If a branch still has its own membership card, in addition to the McDonald's membership card, the store's membership card is also presented.

Cookie content mainly includes: name, value, expiration time, path and domain. The domain can specify a domain such as .google.com, which is equivalent to a main store sign. For example, Procter & Gamble can also specify a specific machine in a domain such as www.google.com or froogle.google.com, you can use rejoice for comparison. The path is the URL path following the domain name, for example, // or/foo. You can use a certain rejoice counter to compare it.
The combination of paths and domains constitutes the scope of cookie.
If no expiration time is set, it indicates that the life cycle of the cookie is the browser session period. When the browser window is closed, the cookie disappears. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again. These cookies are still valid until the preset expiration time is exceeded.

Cookies stored on hard disks can be shared among different browser processes, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods. For IE, pressing Ctrl-N (or from the File menu) in an open window can share the window with the original window, other new IE processes cannot share the memory cookies of opened windows. for Mozilla Firefox0.8, all processes and tabs can share the same cookies. Generally, the window opened with window. open in javascript will share the memory cookie with the original window. The browser often causes a lot of trouble for web application developers who use the session mechanism to process session cookies.


4. Understanding the session mechanism is a server-side mechanism. The server uses a structure similar to a hash (or a hash) to save information.
When the program needs to create a session for a client request, the server first checks whether the client request contains a session id called the session id, if a session id is included, it indicates that a session has been created for this client before, and the server uses the session id to retrieve the session. (if the session id is not found, a new one may be created ), if the client request does not contain the session id, the client creates a session and generates a session id associated with the session. The session id value should be unique, the session id is returned to the client for saving in this response.

Cookie can be used to store the session id. In this way, the browser can automatically display the id to the server according to the Rules during the interaction. Generally, the cookie name is similar to SEEESIONID. For example, for weblogic cookies generated by web applications, JSESSIONID = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764, whose name is JSESSIONID.

Because cookies can be artificially disabled, there must be other mechanisms so that session IDs can still be passed back to the server when cookies are disabled. A frequently used technology called URL rewriting is to directly append the session id to the end of the URL path. There are two additional methods, one is as the additional information of the URL path, the format is http ://..... /xxx; jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764
The other is appended to the URL as a query string, in the form of http: //.../xxx? Jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764
There is no difference between the two methods for users, but they are handled differently by servers during parsing, the first method also helps to distinguish the session id information from the normal program parameters.
To maintain the status throughout the interaction process, the session id must be included after the path that each client may request.

Another technique is form hidden fields. The server automatically modifies the form and adds a hidden field so that the session id can be passed back to the server when the form is submitted. For example, the following form
<Form name = "testform" action = "/xxx">
<Input type = "text">
</Form>
It will be rewritten
<Form name = "testform" action = "/xxx">
<Input type = "hidden" name = "jsessionid" value = "ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764 ">
<Input type = "text">
</Form>
This technology is rarely used now. I have used iPlanet6, the predecessor of the SunONE application server.
In fact, this technology can be simply replaced by rewriting the URL of the action application.

When talking about the session mechanism, we often hear the misunderstanding that "the session disappears as long as the browser is closed ". In fact, you can imagine the example of a membership card. Unless the customer initiates a card sales proposal for the store, the store will never easily Delete the customer's information. The same applies to sessions. Unless the program notifies the server to delete a session, the server will keep it. Generally, the program sends a command to delete the session when the user logs off. However, the browser will never notify the server that it is about to close before it closes, so the server will not have the opportunity to know that the browser has been closed, most session mechanisms use session cookies to save session IDs. When the browser is closed, the session id disappears, and the original session cannot be found when the server is connected again. If the cookie set by the server is saved to the hard disk, or the HTTP request header sent by the browser is rewritten by some means, the original session id is sent to the server, then you can still find the original session when you open the browser again.

It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the seesion. When the last time the session was used by the client exceeds this expiration time, the server considers that the client has stopped the activity before deleting the session to save storage space.

5. Understand javax. servlet. http. httpSession is the Java platform's Implementation specification for the session mechanism, because it is only an interface, specific to the provider of each web application server, in addition to the support for the specification, there are still some minor differences that are not specified in the specification. Here we use the Weblogic Server8.1 of BEA as an example.

Weblogic Server provides a series of parameters to control the implementation of its HttpSession, including the cookie switch option, the URL rewrite switch option, and session persistence settings, set the session expiration time and cookie settings, such as the cookie name, path, domain, and cookie survival time.

Generally, sessions are stored in the memory. When the server process is stopped or restarted, the sessions in the memory are also cleared. If session persistence is set, the server saves the session to the hard disk. When the server process is restarted or the information can be used again, weblogic Server supports persistence methods including file, database, and client cookie storage and replication.

Replication is not stored persistently, because the session is actually stored in the memory, but the same information is copied to the server processes in each cluster, in this way, even if a server process stops working, the session can still be obtained from other processes.

The cookie survival time setting affects whether the cookie generated by the browser is a session cookie. Session cookies are used by default. If you are interested, you can use it to test the misunderstanding we mentioned in section 4.

The cookie Path is a very important option for web applications. Weblogic Server's default processing method for this option makes it significantly different from other servers. We will discuss this topic later.

Vi. HttpSession FAQs
1. When the session is created
A common misunderstanding is that the session is created when a client accesses it. However, the fact is that the session is created until a server program calls HttpServletRequest. A statement such as getSession (true) is created. Note that if JSP is not displayed, <% @ page session = "false" %> disable the session, when the JSP file is compiled into Servlet, the following statement is automatically added: HttpSession session = HttpServletRequest. getSession (true); this is also the source of the implicit session Object in JSP.

Because the session consumes memory resources, if you do not plan to use the session, you should disable it in all JSPs.

2. When the session is deleted
Based on the previous discussion, the session is deleted under the following circumstances. the program calls HttpSession. invalidate (); or B. the interval between the session id sent by the client last time exceeds the session Timeout setting; or c. server process stopped (non-persistent session)

3. How to delete a session when the browser is closed
Strictly speaking, this cannot be done. One way to do this is to use the javascript code window. oncolose on all client pages to monitor the closing action of the browser, and then send a request to the server to delete the session. However, there is no way to break down the browser or forcibly kill the process.

4. Why is there an HttpSessionListener?
You can create listener to monitor the creation and destruction events of sessions, so that you can do some relevant work when such events occur. Note that the listener action is triggered by the session creation and destruction, rather than the opposite. Similar listener related to HttpSession include HttpSessionBindingListener, HttpSessionActivationListener, and HttpSessionAttributeListener.

5. Must the objects stored in the session be serializable?
Not required. Objects are required to be serializable only for the session to be copied in the cluster or to be permanently saved or, if necessary, the server can temporarily swap the session out of memory. If you place an unserializable object in the Weblogic Server session, you will receive a warning on the console. If a session of an iPlanet version that I have used contains an object that cannot be serialized, an Exception occurs when the session is destroyed, which is strange.

6. How can I properly handle the possibility of disabling cookies on the client?
Use URL rewriting for all URLs, including hyperlinks, form actions, and redirection URLs. For more information, see

7. Opening two browser windows to access the application will use the same session or different sessions
For more information, see section 3 on cookie. For session, the session only recognizes IDs and does not recognize people. Therefore, different browsers, different window opening methods and different cookie storage methods will affect the answer to this question.

8. How to Prevent session confusion caused by opening two browser windows?
This problem is similar to preventing forms from being submitted multiple times. It can be solved by setting the token of the client. It means that each time the server generates a different id and returns it to the client and saves it in the session, the client must also return this id to the server when submitting the form, the program first checks whether the returned id is consistent with the value saved in the session. Otherwise, this operation has been submitted. See the section on presentation layer in J2EE Core mode. It should be noted that for the use of javascript window. generally, this id is not set for an open window, or a separate id is used to prevent the main window from being operated. in the open window, modify the settings.

9. Why do I need to call session. setValue again after changing the session value in Weblogic Server?
The main purpose of this operation is to prompt that the Weblogic Server session value has changed in the cluster environment. You need to copy the new session value to other Server processes.

10. Why does the session disappear?
Aside from the normal failure of the session, the server itself may be very unlikely, although I have also encountered some patches in the Solaris version of iPlanet6SP1; the possibility of browser plug-ins is second to that, I have also encountered problems caused by 3721 plug-ins. Theoretically, the firewall or proxy server may also have problems in cookie processing.
Most of the reasons for this problem are program errors. The most common reason is to access another application in one application. We will discuss this issue in the next section.

7. Cross-Application session sharing
This is often the case where a large project is divided into several small projects for development. In order to be able to do not interfere with each other, each small project is required to be developed as a separate web application, in the end, however, we suddenly found that some information needs to be shared between several small projects, or we wanted to use session to implement SSO (single sign on) and save the login user information in the session, the most natural requirement is that applications can access each other's sessions.

However, according to the Servlet specification, the scope of the session should be limited to the current application. Different applications cannot access each other's sessions. Each application server complies with this specification in terms of actual results, but the implementation details may vary. Therefore, the methods for cross-application session sharing vary.

First, let's take a look at how Tomcat isolates sessions between web applications. From the cookie path set by Tomcat, it sets different cookie paths for different applications, in this way, the session IDs used by different applications are different. Therefore, even if you access different applications in the same browser window, the session IDs sent to the server can be different.

8. The summary session mechanism is not complex, but its implementation and configuration flexibility make the specific situation complex and changeable. This also requires us not to regard the experience of a single browser or server as a general experience, but to always analyze the specific situation.
Abstract: Although the session mechanism has been adopted in web applications for a long time, many people still do not know the nature of the session mechanism, and even cannot correctly apply this technology. This article will discuss in detail the working mechanism of the session and answer frequently asked questions about the application of the session mechanism in Java web applications.


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.