About session introduction and the SESSITION method across context (JSP-servlet technology)

xiaoxiao2021-04-03  215

About session and implementation of a session method across context (JSP-servlet technology) Abstract: Although the session mechanism has been used for a long time in web applications, there are still many people don't know the essence of the session mechanism, so that it can't be correct Application technology. This article will discuss the work mechanism of session in detail and give a solution for problems such as the application of the session mechanism in Java Web Application. Directory: First, the term session II, HTTP protocol and status keep three, understand the cookie mechanism, understand the session mechanism 5, understand the Javax.Servlet.http.httpsession 6, httpsession FAQ seven, the session of the cross-adopted program Shared eight, summary reference Document 1, term session in my experience, SESSION This word is abused only in Transaction, more interesting is the meaning of Transaction and Session in certain contexts. Session, Chinese often translates as a session, which means that there is a series of operations / messages that have ended events, such as picking up a phone, dialing to hang up the phone, can be called a session. Sometimes we can see that "during a browser session, ...", the term "session here is why, refers to the opening of this period from a browser window. The most confusing "user (client) is in a session", which may refer to a series of actions of the user (in general, a series of actions related to a specific purpose, such as logging in to purchase goods The process of checking such an online shopping will sometimes be called a transaction, but sometimes it is only a connection, or it may refer to the meaning of the meaning, which can only rely on the context. 2. However, when the session is associated with the network protocol, it often implies two meanings such as "connection" and / or "keep state", "connection" refers to the establishment before communication between communication. A communication channel, such as calling until the other party picks up the phone communication, and this is written, when you go out, you can't confirm that the other party's address is correct, communication channels are not necessarily established But for the sender, communication has begun. "Keep State" means that the communication of communication can associate a series of messages, so that the messages can be dependent on each other, such as one waiter can recognize the old customers who come again and remember the last time this customer still owe a piece of money. . This example has an "a TCP session" or "a pop3 session" 3. In the era of a web server flourishing, Session has new extensions in the language of the web development, and its meaning refers to a solution for maintaining status between client and servers 4. Sometimes Session is also used to refer to the storage structure of this solution, such as "save XXX in session" 5. Since various languages ​​for web development provide support for this solution to some extent, SESSION is also used to refer to solutions for this language in a certain degree of language. The javax.servlet.http.httpsession provided in Java is referred to as Session 6. In view of this confusion, it is no longer changing. The application of the session in this article will also have different meaning according to the context, please pay attention to distinguish.

In this article, express the meaning of the meaning of "SESSION" to express the meaning of "SESSION mechanism", use the "session" expression meaning 5, use the specific "httpsession" to express the meaning 6 II, HTTP protocol The state keeps the HTTP protocol itself is stateless, which is compliant with the HTTP protocol, and the client only needs to download some files to the server, whether it is the client or the server, there is no need to record each other's past behavior. Every request is independent, like a customer and a vending machine or an ordinary (non-member system) supermarket. However, smart (or greedy?) Will soon find that if you can provide some dynamic information generated on demand, it will make the web more useful, just like a game with a TV with a cable TV. On the other hand, this demand is forcing HTML to gradually add client behavior, and on the other hand, the CGI specification appears in the server side to respond to the dynamic request of the client, and the HTTP protocol as the transmission carrier also adds a file upload. , Cookie these features. Where the cookie's role is to solve the efforts of the HTTP protocol stateless defects. As for later SESSION mechanisms, it is another solution that holds a state between the client and the server. Let us use several examples to describe the differences and links between cookie and session mechanisms. The author used a coffee shop for a coffee shop to drink 5 cups of coffee for free, a discount of a cup of coffee, but a one-time consumption of 5 cups of coffee is minimal, then you need some way to record a certain number of customers. Imagine a few options that do not have the following: 1, the store's clerk is very powerful, you can remember the number of consumption of each customer, as long as the customer walks into the coffee shop, the clerk knows how to treat it. This approach is that the agreement itself supports state. 2. Send a card with a card, which records the number of consumption, which generally has a valid period. Each time consumption, if the customer presents this card, the consumption will be linked to the previous or subsequent consumption. This approach is to keep the state in the client. 3, send a member card, in addition to the information other than the card number, no record, each time consumption, if the customer presents the card, the clerk finds the record corresponding to this card, add some consumption information. Add some consumption information. . This approach is to keep the status at the server side. By the HTTP protocol, it does not want to make it in place for all kinds of considerations. Therefore, the following two programs become a reality choice. Specifically, the cookie mechanism uses a scheme that holds a state in the client, while the Session mechanism uses a scheme that holds a status on the server side. At the same time, we also see that since the scheme in which the server is used to keep a status in the client, the SESSION mechanism may need to be saved with the cookie mechanism to achieve the purpose of saving the identity, but in fact it has other options. Third, understanding the basic principles of the cookie mechanism Cookie mechanism is as simple as the above example, but there are several problems need to be resolved: "Member Card" is distributed; "Member Card" content; and how customers use "membership card". Orthodox cookie distribution is achieved by extending the HTTP protocol, the server adds a special instruction to the HTTP's response head to prompt the browser to generate the corresponding cookie in accordance with the instructions. However, pure client scripts can also generate cookies such as JavaScript or VBScript. The use of cookie is automatically sent to the server in the background by a certain principle of a browser. The browser checks all stored cookies, if a cookie declares declares that the range is greater than or equal to the location where the resource to be requested, the cookie is sent to the server on the HTTP request header of the request resource.

It means that McDonald's membership card can only show in McDonald's store. If a branch has released his membership card, then in addition to this store, in addition to showing McDonald's membership card, but also show members of this store. card. The content of cookie mainly includes: name, value, expiration time, path, and domain. The domain can specify a certain domain such as .google.com, which is equivalent to the store signboard, such as P & G, or specify a specific machine under a domain such as www.google.com or froogle.google.com, you can use floating Mercury. The path is to follow the URL path behind the domain name, such as / or / foo, etc., you can use a gentle counter. The path to the domain constitutes the scope of the cookie. If the expiration time is not set, it means that during the browser session, the cookie will disappear as long as the browser window is turned off. This life period is called a session cookie for the browser session. Session cookie generally does not store on the hard disk but is saved in memory, of course, this behavior is not specified. If you set an expiration time, the browser saves the cookie to the hard disk, and turn on the browser again after shutting down, which is still valid until the set expiration time is exceeded. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies saved in memory, different browsers have different ways of processing. For IE, press Ctrl-N (or from the File Menu) on an open window to share with the original window, and the newly opened IE process in other ways cannot share the memory cookie of the open window; for Mozilla Firefox0.8, all processes and tabs can share the same cookie. Generally, the window opened with JavaScript's Window.open will share memory cookies with the original window. The browser is often bothered with a WEB application developer using the session mechanism for session cookie. Below is an example of a GoolGe setting cookie's response header HTTP / 1.1 302 Found location: http://www.google.com/intl/en-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 HTTP Sniffer using Httplook Software to capture a part of the HTTP Communication Record that automatically sends cookies outward when accessing the resources of GoLGEGG Use Firefox to easily observe the existing cookie values ​​Use httplook to fit Firefox can easily understand the working principle of cookies. IE can also be set before accepting cookies This is a question to accept the cookie dialog. Fourth, understanding the session mechanism The session mechanism is a server-side mechanism, and the server uses a structure similar to the hash table (possibly using a hash table) to save information.

When the program needs to create a session for a client request, the server first checks if the request has a session ID - called the session ID, if a session ID already contains, indicating that the client has been previously used Created SESSION, the server follows the session ID to retrieve this session (if the retrieval may be created), if the client request does not include the session ID, create a session for this client and generate a session The value associated with the associated session ID should be a string that is neither repeated, not easy to find the law to be patterned, this session ID will be returned to the client in this response. Save this session ID can use cookies so that the browser can automatically play this identity to the server automatically in the interaction process. Generally, this cookie name is similar to seeesionID, and. For example, WebLogic generated for web applications, jsessionid = BYOK3VJFD75APNRF7C2HMDNV6QZCEBZWOWIBYENLERJQ99ZWPBNG! -145788764, its name is JSessionID. Since cookie can be prohibited, there must be other mechanisms to pass the Session ID back to the server when cookie is disabled. A technique that is often used is called URL rewriting, which is to attach the session ID directly behind the URL path, and there are two additional modes. One is an additional information as a URL path, and the expression is http: // ... ! ../xxx;jsessionid= ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng -145788764 another is as a query string appended to the URL, as a form of http:?! //...../xxx jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng -145788764 these two methods for The user is not distinguished, but the server has different ways to process when parsing, and the first way is also advantageous to distinguish the information of the session ID and the normal program parameters. In order to always keep the state throughout the interaction, this session ID must be included in the path where each client may request. Another technology is called a form hidden field. It is the server automatically modifies the form and adds a hidden field to pass the Session ID back to the server when submitted. For example, the following form

will be rewritten before being passed to the client "form name =" testform "action = "/ xxx"> this technique is now rarely used, the contact I This technique is used in an old IPlanet6 (predecessor of SunOne application servers).

In fact, this technique can be used to replace it with an Action application URL reserved. When talking about the session mechanism, it is often heard such a misunderstanding. "As long as the browser is turned off, the session disappears." In fact, you can imagine an example of a member card, unless the customer actively sells the store, the store will definitely not easily delete the customer's data. The same is true for Session unless the program notifies the server to delete a session, or the server will always reserve, and the program generally send an instruction to delete the session when the user is log off. However, the browser never actively inform the server before it will be turned off, so the server will not have the opportunity to know that the browser has been closed, and there will be this illusion, which is most session mechanism to use session cookies to save the session ID. , After closing the browser, this session ID disappears, and then connect the server again to find the original session. If the cookie set by the server is saved onto the hard disk, or uses some means to overwrite the HTTP request header issued by the browser, send the original session ID to the server, then open the browser again can find the original session. It is precisely because the Close the browser does not cause the session to be deleted, forcing the server to set a fail time for SEESION, when using the session from the client exceeds this failure time, the server can think that the client has stopped activities. The session will be deleted to save storage space. Sustainable continued. . . . (Common Top 2) Introduction to a good article (JSP-Servlet Technology)) (JSP-Servlet Technology)) (Part 2) 5. Understanding Javax.Servlet.http.httpSession HttpSession is a Java platform implementation specification for the session mechanism, because it is only It is an interface, and the provider of each web application server, in addition to the specification support, there will be no specification. Here we use the BEA's WebLogic Server8.1 as an example to demonstrate. First, WebLogic Server provides a series of parameters to control its HttpSession implementation, including switch options using the cookie, using the URL rewritten switch option, session persistence settings, session failure time setting, and each for cookie Settings, such as setting cookies, path, domain, cookie's survival time, etc. Under normal circumstances, the session is stored in memory. When the server process is stopped or rebooted, the session in memory will also be emptied. If the persistence characteristics of the session are set, the server will save the session to the hard disk. When the server process restarts or this information will be able to use again, WEBLOGIC SERVER supports persistence methods include files, databases, client cookies, and replicates. Copy strictly said that persistence is stored, because the session is actually saved in memory, but the same information is copied into a server process within each Cluster, so that even if a server process stops working, it can still be from other processes. Get the session. The setting of the cookie spending time will affect whether the browser generated cookie is a session cookie. By default, session cookies are used. Interested in use it to test the misunderstanding that we mentioned in Section 4. Cookie's path is a very important option for web applications. WebLogic Server's default processing of this option makes it a significant difference from other servers. Behind we will discuss them.

About session settings [5] http://e-docs.bea.com/wls/docs70/webapp/weblogic_xml.html# 1036869 6. HTTPSession FAQ (in this section SESSION's meaning of 5 and 6 mix 1, when the session is created a common misunderstanding that session is created when there is a client access, but the fact is that the statement is now created, pay attention to the statement such as HTTPSERVLETREQUEST.GETSESSION (TRUE) If the JSP does not display <% @Page session = "false"%> Close the session, the JSP file will automatically add such a statement httpsession session = httpservletRequest.getations when compiling into servlets; this is also JSP; The origin of the implied session object. Since session will consume memory resources, if you don't plan to use Session, you should close it in all JSPs. 2. When SESSION is deleted in previous discussion, the session is deleted in the following cases, the program call httpsession.invalidate (); or b. The session ID time interval from the last received client exceeds session timeout Setting; or c. Server process is stopped (non-lasting session) 3, how to delete SESSION strictly when the browser is closed, do not do this. It can be done a little effort to use JavaScript code Window.Oncolose to monitor the closing action of the browser in all client pages, then send a request to the server to delete the session. But these unconventional means for browser crashes or forced killing processes. 4. HTTPSESSIONLISTENER is going on. You can create such Listener to monitor the creation and destruction event of the session so that you can do some work when you have such an event. Note that the session creation and pin destruction move trigger Listener, not the opposite. Similar to HttpSession relating to Listener also has HttpSessionBindingListener, HttpSessionActiVationListener and HttpSessionAttributeListener. 5. Is the object stored in the session must be serialized? It is not necessary. Required objects can serialize just for the session to be copied or can be saved in the cluster or when the Server can temporarily exchange the SESSION. Place an insequential object in the session of WebLogic Server receives a warning on the console. An IPlanet version I have ever used If there is an indemnure-seminated object in the session, there will be an Exception when SESSION is destroyed, which is very strange. 6. How to properly deal with the client to prohibit the possibility of cookie, using the URL override, including hyperlink, form's action, and reset URL, see [6] http: // e-docs .be.com / WLS / DOCS70 / WebApp / sessions.html # 100770 7, open two browser window Access applications will use the same session or different session to see the third section of the third section on the discussion of cookie, for the session Only ID does not recognize people, so different browsers, different window open methods, and different cookie storage methods have an impact on this question.

8. How to prevent users from opening two browser window operations This problem is similar to preventing the form, multiple submission, can be solved by setting the client's token. That is to return to the client each time you generate a different ID, save this ID back to the server while saving the form, and the program first compares the value of the returned ID and the value saved in the session. If it is inconsistent, this operation has been submitted. The "J2EE core mode" can be found on the part of the representation layer mode. It should be noted that this ID is not set to use JavaScript window.open, or use a separate ID to use a separate ID, it is not possible to make a modification operation in Window.open, so you can No setup. 9. Why do you want to re-call a session.setValue after WebLogic Server to do this action is mainly to change the value in the cluster environment, you need to copy new session values ​​to other server processes. . 10. Why did the session do not see the factors that rule the normal failure of the session, the possibility of the server itself should be minimal, although the author has encountered on the Solaris version of IPlanaT6SP1 plus a number of patchs; the possibility of browser plug-ins The author also encountered problems caused by 3721 plugins; theoretically firewall or proxy server may have problems on cookie processing. Most of the causes of this problem is the error of the program. The most common is to access another application in an application. We discussed this issue in the next section. 7. SESSION sharing of cross-adapter procedures often have such a situation, and a large project is divided into several small project development. In order to be able to interfere with each other, each small project is required to be developed as a separate web application, but the last sudden discovery There is a need to share some information between a few small items, or you want to use session to implement SSO (Single Sign On), saving Login user information in the session, the most natural requirement is the application between the applications to access each other's session. However, according to the servlet specification, the SESSION's scope of action should be limited to the current application, and between different applications are unable to access each other's session. Each application server complies with this specification from the actual effect, but the details of the implementation may vary, so the method of solving the use of the SESSION share is also different. Let's take a look at how Tomcat is isolated from the session between the web application. From the Cookie path set by Tomcat, it is different for different application settings, such a session ID used in such different applications. Different, even if different applications are accessed in the same browser window, the session ID sent to the server can also be different. According to this feature, we can speculate that the memory structure in Tomcat is approximately as follows. The IPlanet used by the author also uses the same way, and it is estimated that there will be no difference between SunOne and iplanet. For such a server, the idea is simple, and it is not difficult to practice. Either all applications share a session ID or make the app to get the session ID of other applications. There is a very simple way to implement a shared a session ID, which is set to / (actually there should be / NasApp, which is equivalent to the root) of each application's cookie path.

/ NASAPP Need not to note that the session of the operation sharing should follow some programming agreements, such as the prefix of the application in front of the session Attribute name, make SetAttribute ("Name", "NEO") becomes SetAttribute ("App1.Name", "NEO") to prevent naming spatial conflicts, resulting in mutual coverage. There is no such convenient choice in Tomcat. On Tomcat Version 3, we can also have some pivotes to share session. For Tomcats above version 4, the author has not found a simple approach. Can only be used by means of a third party, such as using files, databases, JMS, or client cookie, url parameters, or hidden fields. Let's take a look at how WebLogic Server handles session. From the screenshot screen, you can see that WebLogic Server sets the cookie's path to all applications, which means that you can share sessions in WebLogic Server. However, a small experiment can prove that even if the same application is used, each application can only access those properties they set. This shows that the memory structure of the session in WebLogic Server may be the following structure, and the problem of SESSION sharing should be impossible on the session mechanism itself. In addition to the means of third parties, such as using files, databases, JMS, or client cookie, url parameters, or hidden fields, there is a more convenient practice, that is, putting an application's session in servletContext, which is another An application can get a reference to the previous application from servletContext. Sample code is as follows, application a context.settribute ("appa", session); application b constexta = context.getContext ("/ appa"); httpsession sessiona = (httpsession) Contexta.gettribute ("appa"); worth paying attention This usage is not portable because the application server can be secure for context.getContext ("/ appa") based on servletContext's Javadoc, return null values, and the above is passed in WebLogic Server 8.1. So why WebLogic Server wants to set all the Cookie paths of all applications? It turns out that for SSO, all applications that share this session can share authentication information. A simple experiment can prove this, modify the descriptor WebLogic.xml of the application that is first logged in, modify the cookie path to / APPA to access another application will re-empt, even in turn, first access the cookie path For /'s application, re-access this modified path, although no time to log in, the user information logged in will also be lost. Note that the authentication method should use Form, because the browser and the web server have other processing methods for the Basic authentication method, and the authentication of the second request is not implemented by session. For details, please refer to [7] Secion 14.8 Authorization, you can modify the attached sample programs to do these trials.

转载请注明原文地址:https://www.9cbs.com/read-131610.html

New Post(0)