Keywords: Web
Requirement: A portal page is required for the company's internal website that was created some time ago. The message center module displays other applications of the company.ProgramThe pending approval record or other content related to the partner. Because you need to avoid directly using URL Redirect (the plaintext of the user name and password cannot be displayed on the URL, which is a bit of a single sign-on ). This requires that the login information be placed in the POST Request body.
Start with session Status Persistence:
I. Term session
Session semantics in the Web development context refers to a type of solution used to maintain the status between the client and the server. Sometimes session refers to the storage structure of this solution, such as "Saving XXX in session ". Various languages used for web development provide support for this solution to a certain extent. Therefore, in a specific language context, session is also used to refer to the solution of this language, for example, the javax. servlet. HTTP. httpsession is short for session.
Ii. http protocol and status maintenance
The HTTP protocol itself is stateless, which is consistent with the original purpose of the HTTP protocol. The client simply needs to request the server to download some files, there is no need to record the previous behavior of each other on both the client and server. Each request is independent, like a customer, a vending machine, or a common (non-membership) the relationships between supermarkets are the same.
But smart (or greedy ?) People quickly found that the Web would become more useful if some dynamic information generated on demand could be provided. Among them, cookies are used to solve the stateless defects of HTTP. As for the later session mechanism, it is another solution that maintains the status between the client and the server.
Let's use several examples to describe the difference and connection between the cookie and session mechanism. I often went to a coffee shop and offered a free discount for five coffee cups. However, there is little chance of consuming five coffee cups at a time, in this case, you need to record the consumption quantity of a customer in some way. Imagine the following solutions:
1. The shop clerk is very good. He can remember the consumption quantity of each customer. As long as the customer enters the coffee shop, the clerk will know how to deal with it. This method is supported by the Protocol itself.
2. Send a card to the customer, which records the consumption quantity and generally has a validity period. For each consumption, if the customer shows this card, the current consumption will be associated with the previous or later consumption. This approach is to maintain the status on the client.
3. Send a membership card to the customer. No information except the card number is recorded. If the customer shows the card at each purchase, then the clerk finds the log corresponding to this card number in the store's record to add some consumption information. This approach is to maintain the status on the server side.
Because the HTTP protocol is stateless and does not need to be stateful for various reasons, the next two solutions have become a realistic choice. Specifically, the cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme. At the same time, we can also see that because the server-side persistence scheme also needs to save an identifier on the client, the session mechanism may need to use the COOKIE Mechanism to save the identifier, but in fact it has other options.
3. Understanding COOKIE Mechanism
The basic principle of the cookie mechanism is as simple as the above example, but there are several problems to solve: how to distribute "membership cards", the content of "membership cards", and how customers use "membership cards ".
The orthodox cookie distribution is implemented by extending the HTTP protocol. The server prompts the browser to generate the corresponding cookie by adding a special line in the HTTP response header. However, pure client scripts such as JavaScript or VBScript can also generate cookies.
Cookies are automatically sent to the server in the background by the browser according to certain principles. The browser checks all stored cookies. If the declared range of a cookie is greater than or equal to the location where the requested resource is located, the cookie is attached to the HTTP request header of the requested resource and sent to the server. This means that the McDonald's membership card can only be presented in the McDonald's store. If a branch still has its own membership card, in addition to the McDonald's membership card, the store's membership card is also presented.
Cookie content mainly includes: name, value, expiration time, path, and domain ). Domain and path determine the range in which cookies can be used, so the cookie on the browser can be named again.
The domain can specify a domain such as .google.com, which is equivalent to a main store sign. For example, Procter & Gamble can also specify a specific machine in a domain such as www.google.com or froogle.google.com, you can use rejoice for comparison.
The path is the URL path following the domain name, for example, // or/Foo. You can use a certain rejoice counter to compare it.
The combination of paths and domains constitutes the scope of cookie.
If no expiration time is set, it indicates that the life cycle of the cookie is the browser session period. When the browser window is closed, the cookie disappears. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again. These cookies are still valid until the preset expiration time is exceeded.
Cookies stored on hard disks can be shared among different browser processes, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods. For IE, pressing Ctrl-N (or from the File menu) in an open window can share the window with the original window, other new ie processes cannot share the memory cookies of opened windows. for Mozilla firefox0.8, all processes and tabs can share the same cookies. Generally, the window opened with window. Open in Javascript will share the memory cookie with the original window. The browser often causes a lot of trouble for Web application developers who use the session mechanism to process session cookies.
The following is an example of how goolge sets the cookie 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
Content-Type: text/html
4. Understanding the session mechanism
The session mechanism is a server-side mechanism. The server uses a structure similar to a hash (or a hash) to save information.
When the program needs to create a session for a client request, the server first checks whether the client request contains a session ID called the session ID, if a session ID is included, it indicates that a session has been created for this client before, and the server uses the session ID to retrieve the session. (if the session ID is not found, a new one may be created ), if the client request does not contain the session ID, the client creates a session and generates a session ID associated with the session. The session ID value should be unique, the session ID is returned to the client for saving in this response.
The cookie can be used to save the session ID. In this way, the browser can automatically display the ID to the server according to the Rules during the interaction. Generally, the cookie name is similar to seeesionid. For example, for WebLogic cookies generated by web applications, JSESSIONID = byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng! -145788764, whose name is JSESSIONID.
Because cookies can be artificially disabled, there must be other mechanisms so that session IDs can still be passed back to the server when cookies are disabled. A frequently used technology called URL rewriting is to directly append the session ID to the end of the URL path. There are two additional methods, one is as the additional information of the URL path, the format is http ://..... /xxx; JSESSIONID = byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng! -145788764 the other is appended to the URL as a query string, in the form of http: //.../XXX? JSESSIONID = byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng! -145788764
There is no difference between the two methods for users, but they are handled differently by servers during parsing, the first method also helps to distinguish the session ID information from the normal program parameters.
To maintain the status throughout the interaction process, the session ID must be included after the path that each client may request.
Another technique is form hidden fields. The server automatically modifies the form and adds a hidden field so that the session ID can be passed back to the server when the form is submitted. For example, the following form
<Form name = "testform" Action = "/XXX">
<Input type = "text">
</Form>
It will be rewritten
<Form name = "testform" Action = "/XXX">
<Input type = "hidden" name = "JSESSIONID" value = "byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng! -145788764 ">
<Input type = "text">
</Form>
This technology is rarely used now. I have used iplanet6, the predecessor of the SunONE application server. In fact, this technology can be simply replaced by rewriting the URL of the action application.
When talking about the session mechanism, we often hear the misunderstanding that "the session disappears as long as the browser is closed ". In fact, you can imagine the example of a membership card. Unless the customer initiates a card sales proposal for the store, the store will never easily Delete the customer's information. The same applies to sessions. Unless the program notifies the server to delete a session, the server will keep it. Generally, the program sends a command to delete the session when the user logs off. However, the browser will never notify the server that it is about to close before it closes, so the server will not have the opportunity to know that the browser has been closed, most session mechanisms use session cookies to save session IDs. When the browser is closed, the session ID disappears, and the original session cannot be found when the server is connected again. If the cookie set by the server is saved to the hard disk, or the HTTP request header sent by the browser is rewritten by some means, the original session ID is sent to the server, then you can still find the original session when you open the browser again.
It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the seesion. When the last time the session was used by the client exceeds this expiration time, the server considers that the client has stopped the activity before deleting the session to save storage space.
5. Understand javax. servlet. http. httpsession
Httpsession is the Java platform's Implementation specification for the session mechanism, because it is only an interface, specific to the provider of each Web application server, in addition to the support for the specification, there are still some minor differences that are not specified in the specification.
Generally, sessions are stored in the memory. When the server process is stopped or restarted, the sessions in the memory are also cleared. If session persistence is set, the server saves the session to the hard disk. When the server process is restarted or the information can be used again.
Replication is not stored persistently, because the session is actually stored in the memory, but the same information is copied to the server processes in each cluster, in this way, even if a server process stops working, the session can still be obtained from other processes.
The cookie survival time setting affects whether the cookie generated by the browser is a session cookie. Session cookies are used by default. If you are interested, you can use it to test the misunderstanding we mentioned in section 4.
Vi. httpsession FAQs
1. When the session is created
A common misunderstanding is that the session is created when a client accesses it. However, the fact is that the session is created until a server program calls httpservletrequest. A statement such as getsession (true) is created. Note that if JSP is not displayed, <% @ page session = "false" %> disable the session, when the JSP file is compiled into servlet, the following statement is automatically added: httpsession session = httpservletrequest. getsession (true); this is also the source of the implicit Session Object in JSP.
Because the session consumes memory resources, if you do not plan to use the session, you should disable it in all JSPs.
2. When the session is deleted
Based on the previous discussion, the session is deleted under the following circumstances. the program calls httpsession. invalidate (); or B. the interval between the session ID sent by the client last time exceeds the Session Timeout setting; or c. server process stopped (non-persistent session)
3. How to delete a session when the browser is closed
Strictly speaking, this cannot be done. One way to do this is to use JavaScript on all client pages.CodeWindow. oncolose monitors the closing action of the browser, and then sends a request to the server to delete the session. However, there is no way to break down the browser or forcibly kill the process.
4. Why is there an httpsessionlistener?
You can create listener to monitor the creation and destruction events of sessions, so that you can do some relevant work when such events occur. Note that the listener action is triggered by the session creation and destruction, rather than the opposite. Similar listener related to httpsession include httpsessionbindinglistener, httpsessionactivationlistener, and httpsessionattributelistener.
5. Must the objects stored in the session be serializable?
Not required. Objects are required to be serializable only for the session to be copied in the cluster or to be permanently saved or, if necessary, the server can temporarily swap the session out of memory. If you place an unserializable object in the WebLogic Server session, you will receive a warning on the console. If a session of an iPlanet version that I have used contains an object that cannot be serialized, an exception occurs when the session is destroyed, which is strange.
6. How can I properly handle the possibility of disabling cookies on the client?
Use URL rewriting for all URLs, including hyperlinks, form actions, and redirection URLs. For more information, see [6].
Http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770
7. Opening two browser windows to access the application will use the same session or different sessions
For more information, see section 3 on cookie. For session, the session only recognizes IDs and does not recognize people. Therefore, different browsers, different window opening methods and different cookie storage methods will affect the answer to this question.
8. How to Prevent session confusion caused by opening two browser windows?
This problem is similar to preventing forms from being submitted multiple times. It can be solved by setting the token of the client. It means that each time the server generates a different ID and returns it to the client and saves it in the session, the client must also return this ID to the server when submitting the form, the program first checks whether the returned ID is consistent with the value saved in the session. Otherwise, this operation has been submitted. See the section on presentation layer in J2EE Core mode. It should be noted that for the use of JavaScript window. generally, this ID is not set for an open window, or a separate ID is used to prevent the main window from being operated. in the open window, modify the settings.
10. Why does the session disappear?
Aside from the normal failure of the session, the server itself may be very unlikely, although I have also encountered some patches in the Solaris version of iplanet6sp1; the possibility of browser plug-ins is second to that, I have also encountered problems caused by 3721 plug-ins. Theoretically, the firewall or proxy server may also have problems in cookie processing.
Most of the reasons for this problem are program errors. The most common reason is to access another application in one application. We will discuss this issue in the next section.