Servlet & JSP (7)

Source: Internet
Author: User
Tags object serialization

This article discusses session management. Once we send a response, the Web service will immediately forget who you are. The next time you make a request, the web server will not know you and will not remember what requests you have made, I don't remember what response I gave you, and my memory is shorter than that of fish. However, for applications such as shopping cart, it is unreasonable for the customer to make a choice and check out in a request. In this regard, what should I do in Servlet?

How do I track users' answers?

We want to complete this function. In the dialog, after a user answers a question, the Web application can ask a new question based on the previous answer. What can we do?

Method 1: Use a stateful session Enterprise JavaBean

Of course, you can make the servlet a client with a stateful Session Bean. Every time a request arrives, you can find the user's stateful bean. What if the provider does not have a complete J2EE server with an EJB container?

Practice 2: Use a database

This works. Every time the customer's data is written into the database, this will lead to poor performance during operation. Therefore, it is not a good choice.

Method 3: Use an httpsession

We can use an httpsession object to save the session Status across multiple requests. That is, the session Status stored in the user throughout the session.

Let's explain how the conversation works with an example of purchasing goods.

1) User A selects an item and the container sends a request to a new servlet thread. The servlet thread discovers the session related to user a and selects her ("milk ") save as an attribute to the session.
2) When the servlet runs its business logic and returns a response, the following question is returned: "What brand ?"
3) User A considers it, selects Mengniu, and clicks submit. The container sends a request to a new servlet thread. The servlet thread discovers the session related to user a and saves his selection ("Mengniu") to the session as an attribute.
4) The servlet runtime business logic returns a response and a problem.

Assume that user B also comes to the shopping website.

5) User A's session is still active, but user B selects "books" and clicks the submit button. The container sends user B's request to a new servlet thread. The servlet thread starts a new session for user B and saves his selection as an attribute to the session.

At this time, we do not want user a and user B's answers to be mixed together, so they need different session objects. Let's answer a question first. How does the container know who the user is?

The HTTP protocol uses stateless connections, which we have mentioned in the Article HTTP parsing. The user's browser establishes a connection with the server, sends a request, receives a response, and closes the connection. That is, the connection is only for one request/response. Because the connection will not be permanently retained, the container cannot recognize that the user of the second request is the same as the user of the first request. Why not use the customer's IP address? Isn't the IP address a part of the request?

For the server, your IP address is the IP address of the router, so you and others in this network have the same IP address, so it is impossible to rely on the IP address. What about HTTPS? If HTTPS is used, the server can recognize the user and associate it with a session. However, this condition is generally not met. Websites do not use HTTPS unless they have specific requirements. Therefore, the customer needs a unique session ID. The principle is simple:

For a user's first request, the container generates a unique session ID and returns it to the user through the response. The user sends this session ID in each subsequent request. After the container sees this ID, it finds the matched session and associates the session with the request.

How do containers exchange session ID information with users?

The container must give the session ID to the user as part of the response in some way. The user must send the session ID back as part of the request. The simplest and most common method is to exchange the session ID information through cookies. Containers perform almost all cookie work, including generating session IDs, creating new Cookie objects, and placing session IDs in cookies.

Send a session cookie in the response using the following statement:

HttpSession session = request.getSession();

This method is not only used to create a session. When this method is called for the first time in a request, a cookie is sent along with the response. It is not guaranteed that the user will introduce cookies, but assume that the customer supports cookies.

Obtain the session ID from the request and use the following statement:

HttpSession session = request.getSession();

This is exactly the same as sending session cookies. So how do I know whether a session already exists or is it just created?

You can call the isnew () method to view details. The Code is as follows:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {response.setContentType("text/html;charset=utf-8");         PrintWriter out=response.getWriter();HttpSession session = request.getSession();if(session.isNew()) {out.println("This is a new session");} else {out.println("Weclome back!");}}

We can use the following statement to determine whether a session already exists.

// If false is passed, this method returns an existing session. If there is no session associated with the customer, nullhttpsession session = request is returned. getsession (false); If (session = NULL) {out. println ("No session was available .. "); out. println ("making one .. "); Session = request. getsession ();} else {out. println ("there was a session .. ");}

What if the browser does not enable cookies? What should we do?

If you do not accept cookies, you can rewrite the URL as a path. If your practice is correct, URL rewriting always works-the customer is not concerned about what happened. You can use URL +; JSESSIONID = 1234567890. Put the session ID at the end of the request URL and return additional information.

// Obtain a session httpsession session = request. getsession (false); // Add the additional session ID information response. encodeurl ("/test. Do") to this URL ");

There may be a situation where you want to redirect requests to another URL, but you want to use a session. For this reason, there is a special URL encoding method:

response.encodeRedirectURL("/test.do");

Note: you cannot rewrite the URL of a static page. You can use URL rewriting only when all pages that are part of a session are dynamically generated. The session ID cannot be hard-coded because it does not exist before running.

How to delete a session?

We certainly do not want the session to be retained, because the session object will occupy resources. The HTTP Protocol does not provide any mechanism for the server to know if the user has gone. How does the container know when the user will go? How can I know when the browser will crash? How do I know when a session can be safely revoked?

There are three methods to terminate a session. White refer, Dagger, poison? No, is 1) Timeout; 2) Call invalidate () on the session object; 3) End of application (crash or cancel deployment ).

Timeout can be set in two ways:

1) Configure session timeout in Web. XML as follows:

<?xml version='1.0' encoding='utf-8'?><web-app xmlns="http://java.sun.com/xml/ns/javaee"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                      http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"  version="3.0"  metadata-complete="true"><servlet><servlet-name>TestServlet</servlet-name><servlet-class>com.shan.web.TestServlet</servlet-class></servlet><servlet-mapping><servlet-name>TestServlet</servlet-name><url-pattern>/Test.do</url-pattern></servlet-mapping><session-config><session-timeout>15</session-timeout></session-config></web-app>

Note: 15 refers to 15 minutes. That is, if the user does not make any request to the session within 15 minutes, the user will kill the session.

2) set the session timeout for a specific session as follows:

session.setMaxInactiveInterval(20*60);

Note: Only for session-specific sessions. The parameters of this method are measured in seconds. If this parameter is set to negative, it indicates that the time is set to infinity.

Call invalidate () on the session object as follows:

session.invalidate();

If the application ends, you don't have to wait. We are looking at the key httpsession methods, as shown in table 1.

  What does it do What do you do with it?
Getcreationtime () Returns the time when the first session was created. We can see how old this session is. You may want to limit the time of some sessions to a fixed period of time. For example, you must finish the form within 10 minutes.
Getlastaccesstime () Returns the time (in milliseconds) for the container to get the last request with this session ID) Determine when the last session is accessed by the user. Use this method to determine whether the user has been away for a long time, and then decide whether to call invalidate () to end the session.
Setmaxinactiveinterval () For this session, specify the maximum interval (in seconds) of user requests) If a user does not make any request to this session after the specified time is passed, the session will be canceled.
Getmaxinactiveinterval () For this session, the maximum time interval (in seconds) for the returned customer request) We can see how long the session remains inactive and remains alive.
Invalidate () End the session. All session property pages currently stored in this session are unbound. If the user is no longer active and the Active session has ended, use this method to end the session.

Table 1 Key httpsession Methods

Can cookies be used only for sessions?

In fact, although the cookie is designed to help support session status, you can also use custom cookies to complete other work. You need to know that cookie is actually a small piece of data (a name-Value Pair) exchanged between the user and the server .) One advantage of cookies is that users do not have to intervene and cookie exchange is automatic (of course, the browser must support cookies ). By default, the cookie is as long as the session life. However, cookies can live longer, even after the browser is closed.

Use servlet API to use cookies

Cookie-related headers can be obtained from HTTP requests and responses, but it is best not to do so. For cookies, all your work has been encapsulated in three servlet APIs: httpservletrequest, httpservletreponse, and cookie.

Create a new COOKIE:

Cookie cookie = new Cookie("username",name);

Set how long the cookie will live on the client:

cookie.setMaxAge(30*60);

Note: The parameter is in seconds. If you set the parameter to-1, the cookie disappears when the browser exits.

Send the cookie to the user:

response.addCookie(cookie);

Obtain one or more cookies from user requests ):

Cookie[] cookies = response.getCookies();for(int i = 0; i < cookies.length; i++) {Cookie cookie = cookies[i];if(cookie.getName().equals("username")) {String username = cookie.getValue();out.println("Hello, " + username);break;}}

Httpsessionbindinglistener

We have talked about the critical moments in the session lifecycle. What if I want to know when a session is added to my attributes? Use the listener. As follows:

Public class dog implements httpsessionbindinglistener {private string breed = NULL; public dog (string breed) {This. breed = breed;} Public String getbreed () {return breed;} public void valuebound (httpsessionbindingevent event) {// I know the code to be run in a session} public void valueunbound (httpsessionbindingevent event) {// I know the code to be run when I am not in a session }}

If an Attribute Class (such as the dog class) implements httpsessionbindinglistener, when an instance of this class is added to or deleted from a session, the container then calls the time processing callback method (valuebound () and valueunbound ()).

Session migration

In a distributed Web application environment, the container balances loads, removes customer requests, and sends requests to multiple JVMs (possibly on the same physical host, or on different physical hosts, we don't care about it ). If each request is made by the same customer, the final request may fail to be handled by a servlet. That is, request a pointing to servlet A may be in one Vm, while request B pointing to servlet A may be in another different VM. What will happen to the servletcontext, servletconfig, and httpsession objects?

Only the httpsession object (and its attributes) will be moved from one VM to another. Each VM has a servletcontext. Each servlet on each VM has a servletconfig. However, for each web application, there is only one http session ID, no matter how many VMS the application is distributed on.

Session MIGRATION PROCESS

The specific process of session migration is as follows:

1) User A selects "milk" and click "Submit. The load balancing server decides to send a request to the container VM-1 in the A-1. Container creates a new session, ID #123. This "JSESSIONID" cookie is sent back to user a in the response.
2) User A selects "electric appliance" and click "Submit. Her request includes "JSESSIONID" #123. This time, the load balancing server decided to send the request to the container VM-2 in the A-2. The container gets the request to see the session ID discover the session in another Vm, that is, the VM-1.
3) Session #123 migrate from the VM-1 to the VM-2 (this session is no longer present in the VM-2 once it is moved to the VM-1 ).
4) The container creates a new thread for the servlet A-2 and associates the new request with the session #123 that just migrated. User A does not know that the new request is sent to this thread, but it is a little delayed during migration.

Httpsessionactivationlistener

Because httpsession may be migrated, it would be better if someone could tell the attributes in the session to move them. If your attributes are directly serializable objects, and you do not care about them, they will be placed there, then this listener may not be used. In fact, most web applications do not use this listener.

Session persistence

If you buy a book online and put it in your shopping cart, the online shop administrator restarts the Web server. When you add a book to the shopping cart again, you find that the previous book information is gone, how do you feel? Therefore, a robust web server provides a session persistence mechanism. This is achieved through object serialization technology. When the session object needs to be reloaded, the session object is re-constructed in the memory through the object deserialization technology. This requires the implementation class of httpsession to implement the serializable interface, and the class of the object stored in the session must also implement the serialization interface.

Several Questions

1) differences between session and cookie

The biggest difference between session and cookie is that session stores information on the server and cookie stores information on the client.

2) Sharing Session cookies

Some may misunderstand that session cookies can be shared between different browser processes by opening browser windows in different ways or using other non-ie browsers. Actually, the Cookies stored in the memory cannot be shared by different browser processes. Sharing can only happen in different windows of the same browser (because these windows share the same process address space ). Cookies stored on hard disks can be shared among multiple browser processes because they are stored on external storage devices.

3) when the browser is closed, the session disappears?

Someone found that, after closing the browser, a new session was started when another browser was opened. In fact, it is mainly because the cookie that saves the session ID is stored in the browser memory. Once the browser is closed, the cookie will be deleted and the session ID will be lost. When you open the browser again to connect to the server, the server cannot find the previous session because it does not receive the session ID. Therefore, the server creates a new session. At this time, the previous session still exists. The session will be cleared only when the set Session Timeout interval occurs. If we save the session cookie to the hard disk, or rewrite the request header sent by the browser to the server
The ID is sent to the server, and the original session is displayed in the browser again.

Reprinted please indicate the source: http://blog.csdn.net/iAm333

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.