first, the term session
Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the phone from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session. Sometimes we can see the words "during a browser session, ...", where the term "session" is used in its original meaning, refers to open from a browser window to close this period ①. The most confusing is the phrase "User (client) during a session", which may refer to a series of actions by a user (typically a series of actions related to a specific purpose, such as a process of online shopping from login to purchase to checkout, sometimes referred to as a transaction) , but sometimes it may just be a connection, or it may refer to the meaning of ①, where the difference can only be inferred by context ②.
However, when the term session is associated with a network protocol, it often implies a "connection-oriented" and/or "hold state" of the two meanings, "connection-oriented" refers to the communication between the two parties before communication to establish a channel of communication, such as telephone, until the other side of the phone communication to start, In contrast to writing letters, when you send out the letter you can not confirm the other person's address is correct, communication channels may not be able to establish, but for the sender, the communication has begun. "Hold state" means that the party of communication can associate a series of messages, so that the message can be interdependent, such as a waiter can recognize the return of the old customers and remember the last time the customer owed a money in the store. Examples of this type are "a TCP session" or "a POP3 session" ③.
With the development of Web server, the semantics of session in the context of web development has been expanded, meaning that it refers to a kind of solution ④ to keep state between client and server. Sometimes the session is used to refer to the storage structure of this solution, such as "Keep XXX in Session" ⑤. Because the various languages used for Web development provide support for this solution to a certain extent, the session is also used to refer to the solution of the language in a particular language context, For example, the javax.servlet.http.HttpSession provided in Java is referred to as Session⑥.
In this article, using the Chinese "browser session" to express the meaning of ①, using the "session mechanism" to express the meaning of ④, using "session" to express the meaning of ⑤, the use of specific "HttpSession" to express the meaning ⑥
second, HTTP protocol and state hold
The HTTP protocol itself is stateless, which is consistent with the HTTP protocol's original purpose, the client simply needs to request to the server to download some files, both the client and the server do not need to record each other's past behavior, each request is independent, Like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.
Yet clever (or greedy?) People quickly discovered that providing some on-demand dynamic information would make the web more useful, like adding on-demand functionality to cable TV. This demand on the one hand, forcing HTML to gradually add the form, script, Dom and other client behavior, on the other hand on the server side of the CGI specification in response to the client's dynamic request, as a transport carrier HTTP protocol also added file upload, cookie these features. The purpose of the cookie is to resolve the HTTP protocol's stateless flaws in the efforts made. The subsequent session mechanism is another solution for maintaining state between the client and the server.
Let's use a few examples to describe the difference and connection between a cookie and a session mechanism. I used to go to a coffee shop to drink 5 cups of coffee free of charge for a cup of coffee, but a one-time consumption of 5 cups of coffee is very little, then need some way to record a customer's consumption quantity. Imagine the fact that there are several options below:
1, the shop clerk is very strong, can remember each customer's consumption quantity, as long as the customer walked into the coffee shop, the clerk knew how to treat. This approach is the protocol itself that supports the state.
2, issued to customers a card, the above record the amount of consumption, there is generally a valid period. If the customer presents this card each time it is consumed, the consumption will be linked to the previous or subsequent consumption. This practice is to keep the state on the client.
3, issued to the customer a membership card, in addition to the card number of what information is not recorded, each time the consumer, if the customer presented the card, the shop clerk in the store records found this card number corresponding record add some consumer information. This is done by keeping the state on the server side.
Since the HTTP protocol is stateless and does not want to be stateful due to various considerations, the next two scenarios become a realistic choice. In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.
third, understand the cookie mechanism
The rationale for the cookie mechanism is as simple as the example above, but there are several issues to be solved: how to distribute the membership card, the content of the membership card, and how the customer uses the loyalty card.
Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, purely client-side scripts such as JavaScript or VBScript can also generate cookies.
And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource. McDonald's membership card can only be presented in the McDonald's store, if a branch also issued their own membership card, then into the store in addition to show McDonald's membership card, but also to show the store's membership card.
The contents of the cookie mainly include: name, value, expiration time, path and domain.
Where a domain can specify a domain such as. google.com, which is equivalent to the head office signs, such as the company, can also specify a domain under a specific machine such as www.google.com or froogle.google.com, can be used to make the ratio of fluttering.
The path is the URL path that follows the domain name, such as/or/foo, and so on, can be used to do a certain float-soft counter. The combination of the path and the domain constitutes the scope of the cookie. If you do not set an expiration time, the cookie will not be in the lifetime of the browser session, as long as the browser window is closed. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires.
Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them. For IE, a window that is opened by pressing CTRL-N (or from the File menu) on an open window can be shared with the original window, while the other way of opening the IE process does not share the memory cookie of the opened window; for Mozilla Firefox0.8, all processes and tabs can share the same cookie. In general, a window opened with JavaScript's window.open will share the memory cookie with the original window. The browser's approach to cookie-only recognition of session cookies is often a major problem for Web application developers who use the sessions mechanism.
Here is an example of a goolge setting a cookie's response header
http/1.1 302 Found location:http://www.google.com/intl/zh-cn/ set-cookie:pref=id=0565f77e132de138:nw=1: Tm=1098082649:lm=1098082649:s=kaeacfpo49ria_d8; Expires=sun, 17-jan-2038 19:14:07 GMT; path=/; Domain=.google.com
Iv. Understanding the session mechanism
The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.
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, and. For example, WebLogic for Web application generation cookie,jsessionid=byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!- 145788764, its name is Jsessionid.
Since cookies can be artificially banned, there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned. A technique that is often used is called URL rewriting, which attaches the session ID directly behind the URL path, and there are two additional ways, which are additional information as a URL path, in the form of 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
These two ways for the user is no difference, but the server in the resolution of the way the process is different, the first way is also conducive to the session ID information and normal program parameters separated.
In order to maintain state throughout the interaction, the session ID must be included after each client may request a path.
Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding 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" >
Before being passed to the client, it will be rewritten as:
This technique is now less applied, and the very old IPlanet6 (the predecessor of the SunOne Application server) that the author has contacted has used this technique.
In fact, this technique can be replaced simply by applying URL rewriting to the action.
When we talk about the session mechanism, I often hear a misunderstanding that "as soon as you close the browser, the session disappears." In fact, you can imagine the membership card example, unless the customer actively to the store to sell cards, otherwise the store will not easily delete customer information. For the session is the same, unless the program notifies the server to delete a session, or the server will remain, the program is generally in the user to log off when sending an instruction to delete the session. However, the browser will never proactively notify the server before shutting down, so the server will not have the opportunity to know that the browser has been shut down, the reason for this illusion is that most of the session mechanism uses a conversation cookie to save the sessions ID, The session ID disappears when you close the browser, and you cannot find the original session when you connect to the server again. If the cookie set by the server is saved to the hard disk, or if a device is used to overwrite the HTTP request header sent by the browser, and the original session ID is sent to the server, the original session can still be found by opening the browser again.
It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for seesion, when the client last time to use the session more than the expiration time, the server can assume that the client has stopped the activity, The session is deleted to save storage space.
v. Understanding Javax.servlet.http.HttpSession
HttpSession is the Java platform for the implementation of the session mechanism specification, because it is only an interface, specific to each Web application Server provider, in addition to the specification support, there will still be some specifications do not specify the subtle differences. Here we demonstrate with Bea's WebLogic Server8.1 as an example.
First, Weblogic server provides a series of parameters to control its implementation of HttpSession, including switch options using cookies, switch options using URL rewriting, session persistence settings, session Expiration time settings, and various settings for cookies, such as setting the name of the cookie, the path, the domain, the lifetime of the cookie, and so on.
In general, the session is stored in memory, when the server process is stopped or restarted, the memory of the session will be emptied, if you set the session's persistence feature, the server will save the session to the hard disk, When the server process restarts or the information will be reused, the persistence methods supported by Weblogic server include file, database, client cookie save, and replication.
Replication is strictly not persisted, because the session is actually kept in memory, but the same information is copied to the server process within each cluster, so that even if a server process stops working, it can still get the session from other processes.
The cookie lifetime setting affects whether the cookie generated by the browser is a session cookie. The default is to use session cookies.
Reference to Settings for session [5] http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036869
vi. httpsession FAQ (in this section the meaning of the session is ⑤ and ⑥ mix)
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. When the session is deleted
A. Program call Httpsession.invalidate ();
or B. Distance from the last received client sent session ID time interval exceeds the session timeout setting;
or C. The server process is stopped (non-persistent session)
3. How to delete the session when the browser is closed
Strictly speaking, do not do this. One way to do this is to use JavaScript code window.oncolose on all client pages to monitor the browser's closing action, and then send a request to the server to delete the session. But there is still nothing to do with the unconventional means of a browser crash or a forced kill process.
4. What's going on with a httpsessionlistener?
You can create such listener to monitor session creation and destruction events so that you can do some work when such events occur. Note that the session creation and destruction actions trigger listener, not the other way around. Similar to the httpsession-related listener and Httpsessionbindinglistener, Httpsessionactivationlistener and Httpsessionattributelistener.
5. 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. Placing a non-serializable object in the session of the WebLogic server will receive a warning on the console. I used a iplanet version. If there are non-serializable objects in the session, it is strange to have a exception when the session is destroyed.
6, 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 [6]
http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770
7, open two browser window access to the application will use the same session or a different session
For the session is to recognize the ID does not identify, so different browsers, different window opening and different ways of storing cookies will have an impact on the answer to this question.
8, how to prevent users to open two browser window operation caused by the session confusion
This problem is similar to preventing multiple submissions of forms, which can be resolved by setting the client's token. is to generate a different ID on the server each time to return to the client, while saving in the session, the client submits the form must be returned to the server, the program first compares the returned ID with the value stored in the session is consistent, if inconsistent indicates that the operation has been submitted. Note that for Windows opened with JavaScript window.open, this ID is generally not set, or use a separate ID, in case the main window can not be manipulated, it is recommended not to window.open open the window to do the modification, so you can not set.
9, why to change the value of session in WebLogic server to re-call once Session.setvalue
The main purpose of this action is to indicate in the cluster environment that the value in the WebLogic server session has changed, and the new session value needs to be copied to the other server processes.
10. Why is the session missing?
Excluding the normal failure of the session, the possibility of the server itself should be minimal, although the author in Iplanet6sp1 plus a number of patches on the Solaris version has been encountered, the browser plug-in second, I have encountered 3721 plug-ins caused by the problem Theoretically, the firewall or proxy server may have problems with cookie processing.
Most of the reasons for this problem are procedural errors, and the most common is to access another application in one application.
Vii. Cross-application session sharing
A, either let all applications share a session ID, or allow the application to get the session ID of the other application.
It should be noted that the session of the operation sharing should follow some programming conventions, such as prefix the session attribute name with the application, so that setattribute ("name", "Neo") becomes setattribute (" App1.name "," Neo ") to prevent namespace collisions, resulting in overwriting each other.
b, with the help of third-party forces, such as the use of files, databases, JMS or client cookie,url parameters or hidden fields and other means, there is a more convenient way, is to put an application session into the ServletContext, This allows another application to get a reference from the previous application from ServletContext.
Javaweb---Summary (19) session mechanism