session

xiaoxiao2021-03-05  24

Abstract: Although the session mechanism has been used for a long time in web applications, there are still many people unclear the essence of the session mechanism, so that this technology cannot be applied. 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 out such an online shopping will sometimes be referred to as a transaction, but sometimes it is also just a connection, or it may refer to the meaning of 1, where the difference can only be inferred 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, Session in the Web development context has a new extension, and its meaning refers to a solution for a state of maintaining a state between the client and the server 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?) People quickly discovered that if you can provide some dynamic information generated on demand, it will make the web more useful, just like a TV with the cable TV. On the other hand, this demand is forcing HTML to gradually add a form, script, and DOM and other client behavior. On the other hand, the CGI specification appears in the server side to respond to the client's dynamic request, and the HTTP protocol as a 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. Since the HTTP protocol is stateless, it does not wish to make it a state due to various considerations, and therefore, the following two programs become a reality choice. Specifically, the cookie mechanism uses a scheme that keeps a state in the client, and the Session mechanism is a scheme that holds a state in the server side. At the same time, we also see that the SESSION mechanism may need to be saved by means of a cookie mechanism because the scheme is required to hold a logo in the client, so the SESSION mechanism may need to achieve the purpose of saving the identity by means of a cookie mechanism, 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, the life period of this cookie is the browser session, as long as the browser window is turned off, cookies disappeared. 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 expiration time is set, the browser saves the cookie to the hard disk. After turning off, open the browser again, which is still valid until the setting 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 opened 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 goelge set of cookie's response header HTTP / 1.1 302 FoundLocation: 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.comcontent-type: text / html This is using httplook HTTP Sniffer software A part of the captured HTTP Communication Record is automatically sent to the outside to access the Goolution resource again. Cookie Use Firefox. You can easily observe the value of the existing cookie Use httplook to match Firefox. You can easily understand the working principle of cookie. 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, add a hidden field to pass the session ID back to the server when you submit. 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, I contacted This technique is used in an old IPlanet6 (predecessor of SunOne Application Server). 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 takes the initiative to sell the store, the store will definitely not easily delete the customer's information. 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. 5. Understanding javax.servlet.http.httpSessionHttpSession is a Java platform to implement a specification of the session mechanism, because it is just an interface, specifically to each web application server provider, in addition to the standard support, there will still be some specification There is no specified thin difference. 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. The copy is strictly said that it is not allowed to save, because the session is actually saved in memory, but the same information is copied into the server process in each Cluster, so that even if a server process stops work, it is still 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 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 destruction movements 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 correctly pay the client to prohibit the possibility of cookie from using the URL to override, including hyperlink, form's action, and redirected URL, see [6] http: // e-DOCS .bea.com / WLS / DOCS70 / WebApp / sessions.html # 1007707, open two browser window accessing the application 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 is only Id 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 issue is similar to preventing forms from multiplexing 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 when you save the form, and the program is first compared to the value of the ID and the value saved in the session. If it is inconsistent, this operation has been submitted. You can see the "J2EE core mode" about 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 after the value of the session in WebLogic Server, you want to recall the session.setValue to do this action. This action is mainly to change the value in the weblogic server session 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 actually. 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.

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

New Post(0)