Introduced a session on the good articles, written in great detail (jsp-servlet technology)
Abstract: This paper presents a session on the good articles, written in great detail (jsp-servlet technology)
Abstract: Although the session mechanism in the web application has been used in a long time, but there are still many people do not know the nature of session mechanism, and not the correct application of this technology. This session will be discussed in detail and a working mechanism in the Java web application in the application session mechanism frequently asked questions to answer.
Contents:
1, terminology session
Second, the HTTP protocol and the state to maintain three, four understanding cookie mechanism, the mechanism of understanding session, understanding javax.servlet.http.HttpSession
6, 7 HttpSession common, cross-application sharing session of the G-8, the reference document summary
1, terminology session
In my experience, the session was the word about the extent of the abuse after the transaction, the transaction is more interesting session and, in some context is the meaning of the same.
Session, the Chinese translation for the regular session, its original meaning refers to the conclusion of a series of moves / information, for example, pick up the phone call from the telephone dial-up to hang up the middle of a process that can be called a session. Sometimes, we can see that this case "in a conversation during ,…", browser session here is the term used in its original meaning, refers to a browser window open to the closure of this period â‘ . The confusion is the most "user (client) in a session during" such a word, it may be a series of moves that users (under normal circumstances with a specific purpose related to a series of moves, such as the purchase of goods from listing to settle accounts online shopping publish such a process, sometimes known as a transaction), but sometimes may be merely refers to a connection, may also refers to the meaning â‘ , the difference can only rely on context to infer â‘¡ .
However, when the session word associated with the network protocol, it is often implied a "connection-oriented" and / or "maintain status" This two meanings, "connection-oriented" refers to the communication prior to the two sides in the communications to establish a communication channel, such as the call to the other side until the telephone communication can begin, and this is the relative wrote in the letter sent to you when you and the other party could not confirm the address is correct, not necessarily communication channels can be established, but the sender, the communication has already begun. "Keep state" refers to the communications side of a series of related information, can be made between the co-dependent information, such as a waiter to recognize once again the old customers coming and remember that the last time a store customers still owe money . Examples of this type of "one TCP session" or "a POP3 session" â‘¢.
And the web server to the era of vigorous development, web session in the context of the development of the semantic there has been a new, and its meaning is in a class for the client and server to maintain state solution ④. Sometimes session also used to refer to this solution storage structure, such as the "xxx stored in the session," ⑤. Because of the language used in web development to a certain extent provided for the support of this solution, in the context of a particular language, the session has also been used to refer to the language of the solutions, such as regular Java, to provide for short session ⑥ javax.servlet.http.HttpSession.
In view of this confusion has been irrevocably, in this session will be in accordance with the use of the term means different context, attention to the resolution.
In this paper, the use of Chinese "browser session during" ①meaning to the expression, the use of "session mechanism" ④ meaning to the expression, the use of "session" ⑤ meaning of the expression, the use of specific "HttpSession" to express the meaning ⑥
Second, the HTTP protocol and maintain state
HTTP protocol itself is not the state, and the HTTP protocol is in line with the original purpose, the client need only a simple request to the server to download certain documents, regardless of the client or the server is not necessary to record all their past behavior, and every time between requests are independent, just like a customer and a vending machine or an ordinary (non-member system), like the relationship between the store.
However clever (or greedy?) If people can quickly discovered some on-demand generation of dynamic web information will become more useful, like cable television to function with the same demand. On the one hand, this demand gradually added to HTML forms, scripts, such as DOM client, the server-side on the other hand, could lead to the CGI specification in response to client requests the dynamic, as a transmission vector of the HTTP protocol also added file uploading , cookie These features. Cookie which is the role of non-HTTP protocol to address the state of the efforts made by the defect. As for the later session is also a mechanism for the client and server to maintain state solution.
Let us use a few examples to describe the session cookie mechanism and the differences and similarities between. I once frequented a coffee shop to drink five cups of coffee are free gifts for a cup of coffee, but a one-time 5 cups of coffee consumption little chance, and you have a need for some way to record a customer's consumption volume. Imagine actually Mowaihu following several options:
1, the shop's staff is formidable, can remember the consumption of each customer, as long as customers walked into a coffee shop, the staff members know how to deal with the. This approach is the agreement to support the state.
2, give customers a card, the above record of the number of consumption, there are a general validity. Each consumer, and if customers show this card, and the consumer will be before or after linked to the consumer. This approach is maintained in the client state.
3, give customers a membership card, in addition to numbers from the message or records, each consumer, and if customers to produce the cards, the records clerk in the store found on the numbers of the corresponding records add some consumer information. This approach is maintained in the server-side state.
Since the HTTP protocol is stateless, and, due to various considerations do not want to become a state and, therefore, behind the two plans have become realistic option. Specifically cookie mechanism is used to maintain client state in the programme, and the session is the mechanism used to maintain state in the server-side options. At the same time we have also seen, as a result of server-side state maintained in the client's programme also need to keep a logo, it may need the help of mechanisms session cookie mechanism to achieve the purpose of preserving logo, but actually there are other options.
Third, understanding cookie mechanism
Cookie mechanism on the basic principle as in the above example as simple, but there are still a few problems to be solved: "membership card" to distribute "membership card"; customers, as well as how to use the "membership card."
Orthodox cookie circulated through the extension of the HTTP protocol to achieve, through the HTTP server response in the head with his special instructions to the browser tips generated in accordance with the instructions of the cookie. However, the client simply as JavaScript or VBScript scripts can be generated cookie.
And the cookie use by the browser according to certain principles in the background automatically sent to the server. Check all storage browser the cookie, if a cookie statement by the role of the request will be more than equal to the location of the resources, put the cookie request resources attached to the head of the HTTP request sent to the server. McDonald's is the meaning of the membership card in the McDonald's store can only produce, if a certain stores also issued their own membership card, then into the shop this time in addition to the McDonald's to produce membership cards, but also to produce this shop Member card.
Cookie features include: name, value, measured by time, path and Victoria.
One domain can specify a particular domain, for example. Google.com, or Honten signs, such as Procter & Gamble, can also designate a specific domain of a machine such as www.google.com or froogle.google.com, can float Sophie than done.
Path is in the domain name back to the URL path, such as / or / foo, etc., it can be done than a Piaorou counters.
Path and Victoria together constitute the role of the cookie.
If we do not set time expired, says the cookie period of the life of the browser session, as long as the closure of the browser window, cookie disappeared. This period of life browser session of the cookie is called the session cookie. Session cookie does not generally stored in the hard disk stored in memory, but, of course, such acts were not the norm requirements. If the installation of the expired time, the browser will be the cookie saved to the hard drive, open again after the closure of the browser, these cookie remains valid until exceeds a set time expired.
Stored in a cookie on your hard disk can be in different browser sharing process, such as two IE window. For memory stored in the cookie, different browsers have different approach. For IE, in an open window press Ctrl-N (or from the File menu) to open the window can be shared with the original window, and the use of other means of a new process can not share IE has opened a window of memory cookie For Mozilla Firefox0.8, all the processes and tab can share the same cookie. Generally speaking, it is using the window.open javascript window will open with the original cookie shared memory window. Browser session cookie for this cookie is not only recognized in the way of identification to use the regular session mechanism web application development caused great distress.
Below is a response to the cookie goolge first set examples
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
Content-Type: text / html
This is the use of this HTTPLook HTTP Sniffer software to capture the part of the HTTP communication records
Browser in another visit goolge resources automatically sent out cookie
Using Firefox can easily observe the existing use of the value of the cookie with Firefox HTTPLook can easily understand the working principle of cookie.
IE can be set up in the cookie before asked
This is a dialog box asked to accept the cookie.
Fourth, understanding mechanisms session
Session mechanism is a server-side mechanism, the server uses a structure similar to the hash table (and might also be used hash table) to store information.
When the process requires a client to create a session at the request of the time, the server first inspection at the request of the client, whether it has included a session logo - known as the session id, if included a session id is illustrated in the past has been for the client creation of a session, in accordance with the session id on the server to search out the use of this session (if not retrieved, the new one may be), if the request does not contain client session id, for the creation of a client generates a session and this session associated session id, the session id value will not be a repeat, was not easy to find copies of the string, the session id will be in this response back to the client preservation.
Preserve the session id way cookie can be used, the interaction of this browser can automatically in accordance with the rules of this logo play to the server. The general's name is similar to the cookie SEEESIONID,. For example, the web application weblogic generated cookie, JSESSIONID = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764, And its name is JSESSIONID.
The cookie can be artificially prohibited, there must be other mechanisms to be banned in the cookie still be able to transfer back to the server session id. Often use a technique called URL rewriting, the session id is directly attached to the URL path behind, and there are also two additional, as a URL path additional information, the form of http:// … .. / xxx; jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764
Another is a query strings attached to the URL behind, and the form of http://…../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764
For users of these two methods is no different, only the server in the analysis of different ways to handle the course, the first approach is conducive to the session id information and the normal procedure to separate parameters.
In order to the whole process of interaction always maintain state, we must each client may request the path behind contain this session id.
Another technology called hidden form fields. Is the server will automatically modified form, add a hidden field, in order to form submitted to the session id transfer back to the server. For example, the form below
<form Name="testform" action="/xxx">
<input Type="text">
</ Form>
In the transfer to the client before will be rewritten as
<form Name="testform" action="/xxx">
<input Type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764">
<input Type="text">
</ Form>
The technology is now less application, the author contacted the very oldest iPlanet6 (formerly SunONE Application Server) on the use of this technology.
In fact this technology can be used for simple applications URL rewriting action to replace.
Talking about the session mechanism, often heard of such a misunderstanding, "as long as the close your browser session disappeared." In fact, a membership card conceivable example, unless the customers take the initiative to put stores selling cards, stores will not otherwise easily delete customer information. On the session, is the same, unless notification of the proceedings to delete a session server, or the server has been retained, and procedures are generally done in the user log off when the instructions to delete session. However, the browser has never taken the initiative prior to closure notice will be closed server, the server will not have the opportunity to know that the browser has been closed, and the reason there is such a misconception is that most session mechanisms to preserve the use of the session cookie session id , and close your browser after this session id disappeared again connects to the server when it could not find the original session. If the server set up a cookie is saved to the hard drive, or use a browser means rewrite HTTP requests issued by the head of the original session id sent to the server, open the browser again can still find the original session.
It is precisely due to the closure will not result in the browser session was deleted, forcing seesion set up a server for a time lapse, when the distance between the client session on the first use of the time over the failure time, the server can be considered a client has stopped, the session will be deleted in order to save storage space.
5, understanding javax.servlet.http.HttpSession
HttpSession session on the Java platform is the realization of standardized mechanism, because it is just the interface, specific to each web application server providers, in addition to standard support, there will still be some norms, does not require the nuances. Here we BEA's Weblogic Server8.1 as an example to demonstrate.
First, Weblogic Server provided a series of parameters to control the realization of its HttpSession, including the use of cookie switching options, the use of URL rewriting the switch option, the establishment of lasting session, the time lapse session settings, as well as for cookie the various settings, such as setting cookie name, path, domain, cookie survival time.
Under normal circumstances, the session are stored in the memory, when the server was stop or restart the process when the memory of the session will be empty, and if the settings of the session lasting characteristics of the server session will be saved to your hard disk , restart the server process or information will be able to be used again, Weblogic Server support for a lasting manner, including documents, databases, client cookie preservation and reproduction.
Copy lasting preservation is not, strictly speaking, because session is still stored in memory, but the same message was copied to all servers within the cluster in the process, even though such a process server can still stop work from the other process in session.
Cookie survival time in the browser settings will affect whether generated cookie is a session cookie. The default is to use the session cookie. Interest can be used to test in the fourth quarter, we mentioned that misunderstanding.
Cookie path for the web application is a very important option, this option Weblogic Server on the default approach with other server makes it clear distinction. Later we will discuss this issue.
On the session settings reference [5] http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html # 1036869
6. HttpSession FAQ (in this section for the meaning of the session and ⑥ ⑤ the mix)
1, when the session was to create a common misconception is that the session in a client visit was created, but the fact is until the end of a server program called HttpServletRequest.getSession (true) such a statement when it is created, the attention If no session JSP <% @ page session = "false"%> closed session, the JSP document will be compiled into Servlet automatic inclusion of such a statement HttpSession session = HttpServletRequest.getSession (true); This is in JSP implied the origins of the session object.
The session will consume memory resources and, therefore, if we do not intend to use session, it should be in all of the JSP close it.
2, when the session was deleted before the comprehensive discussion session in the following circumstances be deleted a. procedure call HttpSession.invalidate (); or b. received from a client, the session id sent over a time interval of the super-session When installed, or the process of being suspended c. server (non-durable session)
3, in the browser how to delete the closed session,
Strictly speaking, this is not done. That can be done through the efforts of all the client pages, the use of javascript code browser window.oncolose to monitor the closure moves, and then send a request to the server to delete the session. But for the browser crash or forced to kill the process of these unconventional means still powerless.
4, there is a HttpSessionListener thing is how you can create such a monitoring session listener to the creation and destruction of the incident, making in the event of such incidents, you can do some corresponding work. Attention is the creation and destruction of the session moves trigger listener, and not the contrary. Similar HttpSession and the listener also HttpSessionBindingListener, and HttpSessionAttributeListener HttpSessionActivationListener.
5, stored in a session must be focused on the sequence of it may be not necessary. Object can be requested only for sequences of the session in the cluster can be copied or lasting preservation or, if necessary, to temporarily server session to exchange memory. Weblogic Server in the session placed an object in the sequence of the console will receive a warning. I used a iPlanet version is not in session if the sequence of the target of destruction in the session there will be an Exception, very strange.
6, how to deal with the right cookie client the possibility of prohibiting all use of URL rewriting the URL, including hyperlinks, the action form, and redirect the URL, of the specific approach, see [6]
Http://e-docs.bea.com/wls/docs70/webapp/sessions.html # 100770
7, a visit to the two browser window applications will use the same or a different session session
See section on the third cookie discussions, the session id is not only recognition of identification, different browsers, different methods and different window open the cookie storage on this issue will affect the answer.
8, how to prevent the user to open two browser window operation of the session led to confusion and prevent this problem is similar to the form many times, the client can be set up to solve the token. Each server is in a different generation id back to the client, while preserving the session, the client must submit this form id also returned to the server, the first procedure compared with the return of id kept in session, the value of consistency If this inconsistency is illustrated in operation has been submitted before. Can see "J2EE core model" on the part of that layer model. It must be noted that the use of javascript window.open open window, generally do not set the id, or use a separate id to prevent the main window inoperable proposal not to open the window, window.open modified, enabling not installed.
9, why the change in the Weblogic Server session in the value of re-call after a session.setValue
To do this is to move in the cluster environment Weblogic Server session suggested that the value has changed, the need for the process to other servers copy of the new session.
10, why exclude session session disappeared normal failure factors, the possibility of the server itself is minimal, although the author iPlanet6SP1 increase the number of patches on the inverted version of Solaris also encountered; browser plug-ins, the possibility of The author also encountered problems caused by plug-in 3721; theoretically firewall or proxy server in the cookie handling may also be a problem.
Most of this issue there are reasons for the wrong procedure, the most common is an application program to access another application. We discussed this issue in the next section.
7, the cross-application sharing session
Often this is the case, a large number of projects cut into small-scale development projects, in order to Noninterference for each small projects as a separate web application development, but in the end suddenly discovered a few small projects between the need to share some of the information, or you want to use to achieve session SSO (single sign on), preserved in the session the user login information, the request is the most natural applications of the session to visit each other.
Servlet However, in accordance with norms, the role of the session should be limited to the current application procedures, between different applications can not visit each other in each other's session. Individual applications on the server are from the actual results to comply with this standard, but realize it may be the details vary, address cross-application sharing session of the different methods.
Tomcat is the first look at how to achieve session between web application isolation, and set up the Tomcat from the cookie path, it set up different applications of the cookie path is different, so different applications used by the session id are different, so even in a browser window with visiting different applications, sent to the server session id can be different.
Based on this characteristic, we can speculate Tomcat session in the memory structure is as follows.
The author previously used iPlanet also use the same way, it is estimated that between SunONE iPlanet and there will not be much difference. For this type of server, the solution is very simple idea, the actual practice will not be difficult. Either to allow all applications share a session id, or allow applications to access other applications of the session id.
IPlanet there is a very simple way to achieve a shared session id, and that is all the applications are set cookie path / (actually should be / NASApp, speaking for the application equivalent to its role root). / NASApp
It must be noted that the operation of sharing some programming session should follow the agreement, for example, in the previous session attribute names with the prefix applications, making setAttribute ( "name", "neo") into setAttribute ( "app1.name , "" neo "), in order to prevent namespace conflicts, leading to mutual coverage.
In the Tomcat is not so convenient choice. In Tomcat version 3, we can also have some means of sharing session. The Tomcat version 4 or above, I have not yet found a simple solution. With only the strength of a third party, such as the use of documents, databases, JMS client or cookie, URL parameters or hidden fields, and other means.
We look at what Weblogic Server is how to deal with the session.
Screenshots from the screen can be seen on all the Weblogic Server application settings cookie paths / This is not meant in the Weblogic Server in default on the session can be shared? However, a small experiment can be proven even if different applications using the same session, individual applications can only access their own set of attributes. This shows that the session Weblogic Server memory structures could be as follows
For such a structure, in a session of the mechanism itself solve the problems should be shared session is not possible at all. In addition to the help of third-party force, such as the use of documents, databases, JMS client or cookie, URL parameters or hidden fields, and other means, there is a more convenient way is to bring an application into the ServletContext of the session, so Another application can be obtained from the ServletContext before an application procedures are cited. Examples of the code below,
A applications
Context.setAttribute ( "appA" session);
Application B
ContextA = context.getContext ( "/ appA");
HttpSession sessionA = (HttpSession) contextA.getAttribute ( "appA");
It is worth noting that such usage of the transplant, because according to the ServletContext JavaDoc, application servers can be in for security reasons context.getContext ( "/ appA"); returned to the null value, the above practices adopted by the Weblogic Server 8.1.
So why should all Weblogic Server Application procedures are set cookie path /? SSO is to the original, all sharing this session of the application can be shared authentication information. A simple experiment can prove this point, to amend the First Sign that the application procedures described at weblogic.xml the cookie path to amend / appA visit another application requirements will be re-login, even contrary, to visit the cookie path to / applications, changes have been made to re-visit this path, although no longer tips log, but logged in user information will be lost. Pay attention to this experiment, FORM authentication methods should be used, because the browser and the web server on the basic authentication method there are other ways of dealing with the second request certification is not achieved through the session. Please refer to the specific [7] secion 14.8 Authorization, you can modify the examples accompanying procedures to do these tests.
8. Summary
Session mechanism itself is not complicated, but the realization of its configuration and the flexibility of the specific situation makes it complicated and changeable. This also requires us not only to a certain time or a certain experience in the browser, server experience as a universally applicable experience, but always specific needs of specific situations.
Abstract: Although the session mechanism in the web application has been used in a long time, but there are still many people do not know the nature of session mechanism, and not the correct application of this technology. This session will be discussed in detail and a working mechanism in the Java web application in the application session mechanism frequently asked questions to answer.
↑ Back
Tags: java session






