The difference JavaWeb of Cookie and Session

The difference between Cookie and Session

First, the difference between the mechanism and the session cookie mechanisms

*************************************************************************************

Specifically, the cookie mechanism uses a client program on hold, but the mechanism used to maintain session state on the server side program. We also see that because only the server to maintain state program on the client also needs to save a logo, so session cookie mechanisms may need the help of mechanisms to achieve the purpose of preservation of identity, but in fact there are other options, such as heavy write URL and hidden form fields.

 

*************************************************************************************

Second, the difference between the session cookie and persistent cookie

*************************************************************************************

 

If you do not set an expiration time, it means that the cookie life cycle during a browsing session, simply close the browser window, cookie disappeared. This period of life of the browsing session cookie is called a session cookie. General session cookie is not saved on the hard disk, but kept in memory.

 

If you set the expiration time (setMaxAge (60 * 60 * 24)), the browser cookie will be saved to your hard drive, open the browser again after closing, these cookie remain valid until the expiration time exceeds the set. cookie stored on the hard disk can be shared between different browser process, such as two IE windows. For cookie stored in memory, different browsers have different approach. (Test passed in IE)

 

*************************************************************************************

Third, how to use the Cookie automatic logon

*************************************************************************************

 

When users register on a website, you will receive a unique user ID cookie. Later, when the client reconnects, the user ID is automatically returned, the server examines it to determine if it is a registered user and the selected automatic login, allowing users to give a clear business need a username and password, you can access on the server resources.

 

*************************************************************************************

Fourth, how to customize the site based on user's preference

*************************************************************************************

 

Site can use cookie records the user's wishes. For simple setup, the site can directly store the settings page to complete the custom in a cookie. However, more complex settings for page customization, the site will need only send a unique identifier to the user by the server-side database storage corresponding to each identifier.

 

*************************************************************************************

Five, cookie sent

*************************************************************************************

 

1. Create a Cookie object

2. Set the maximum age

3. The Cookie header into the HTTP response

 

If you create a cookie, and sends him to the browser, by default it is a session-level cookie: automatically create a cookie and jsessionId stored in memory (as a server browser, the value of the key as the value sessionId sent to the client browser memory), the user is deleted after you quit the browser. If you want the browser the cookie is stored on disk, you need to use maxAge, and gives a time in seconds. The biggest limitation is set to 0 is the command browser to delete the cookie. Transmitting the cookie need addCookie HttpServletResponse method, the cookie is inserted into a Set-Cookie HTTP request header. Since this method does not modify any previously specified Set-Cookie header, but create a new header, so we called this method is addCookie, rather than setCookie. Also keep in mind before setting response headers must be sent to the client in any document content.

 

*************************************************************************************

Six, cookie read

*************************************************************************************

 

1. Call request.getCookie

To get the browser has sent the cookie, getCookies HttpServletRequest method needs to be called, the call returns an array of Cookie objects, Cookie header value should be entered for the HTTP request.

 

2. circulation of the array, calling getName methods for each cookie until you find the cookie of interest, cookie associated with your host (domain), rather than your servlet or JSP page. Thus, although your servlet may only send a single cookie, you might also get a lot of irrelevant cookie.

For example: (login.jsp page cookie implement user name userName fill)

login.jsp:

 

<%

String username = "";

        // read cookie files on your hard disk from a client

         Cookie[] cookies = request.getCookies();

       if(cookies == null){

           username = "";

        }

       else{

          for (int i = 0; i < cookies.length; i++){

                 if ("USERNAME".equalsIgnoreCase(cookies[i].getName())){

                   username = cookies[i].getValue();

               }

       }

%>

 

<form name="login" method="post" action="login.do">

      <td width="100%" bgcolor="#CCCCCC" colspan="2">

   <P align = "left"> User Name <br>

              <input type="text" name="username" value= "<%=username%>">

      </p>

      <p align="left">密 码 <br>

              <input type="password" name="password">

      </p>

       <p align="left">

         <input type="submit" name="Submit" value="确定">

         <input name="reset" type="reset" value="取消">

       </p>

</form>

 

LoginAction:

              // put the correct userName c1 object and use "USERNAME" do key identifier

             Cookie c1= new Cookie("USERNAME",logindto.getUsername());

               // If you do not set the time, the cookie is a session cookie, is not written to the client hard disk

               c1.setMaxAge(60*60*24);  

                response.addCookie(c1);

 

*************************************************************************************

Seven, how to use a cookie to detect first-time visitors

*************************************************************************************

 

A. calls HttpServletRequest.getCookies () Gets an array of Cookie

B. retrieve the specified name in circulation cookie exists and the corresponding values ​​are correct

C. If you exit the loop and set distinctive identity

D. whether the first-time visitor to perform different operations in accordance with the difference determined user identifier

 

*************************************************************************************

Eight Common Mistakes use cookie detection of first-time visitors

*************************************************************************************

 

Just because cookie does not exist in a particular array of items it considers a first-time visitors. If the cookie array is null, the client may be a first-time visitors, it may be because the user cookie to remove or disable results caused. However, if an array of non-null, but also show the customer visited your site or domain, it does not mean they have visited your servlet. Other servlet, JSP pages, and non-Java Web applications can set a cookie, based on path settings, which are likely to return any cookie to the user's browser.

 

The correct approach is to determine whether the cookie array is empty and that the specified value and the Cookie objects correctly.

 

*************************************************************************************

Nine, using the cookie property of attention problems

*************************************************************************************

 

Attribute is part of header sent from the server to the browser; however, they are not returned by the browser to the server header.

 

Thus in addition to the name and value, cookie attribute applies only the output from the server to the client's cookie; server cookie from the browser does not set these properties. So do not expect this property can be used by cookie request.getCookies obtained. This means that you can not just by setting the maximum age of the cookie, sent it, find the appropriate cookie in subsequent input array, read its value, modify it and store it Cookie, in order to achieve cookie value changing.

 

*************************************************************************************

Ten, how to use a cookie record of each user access count

*************************************************************************************

 

1. Obtain the value of the cookie cookie array designed for users of statistics the number of visits

2. Value is converted to type int

3. The value plus 1 and re-create a Cookie object with the original name

4. Re-set the maximum age

5. The new output cookie

 

*************************************************************************************

Eleven, session different meanings in different contexts

*************************************************************************************

 

the session, often translated into Chinese session, its original meaning refers to a series of operations / message beginning and an end, such as dialing the phone call is picked up from the middle to hang a series of processes can be called a session. However, when the term session protocol associated with the network, it often implies a "connection-oriented" and / or the meaning of two such "hold."

 

Semantic Web session in the development environment has a new extension, its meaning refers to a class of solutions used to maintain state between client and server. Sometimes Session also used to refer to the storage structure of such a solution.

 

*************************************************************************************

Twelve, session mechanism

*************************************************************************************

 

session mechanism is a mechanism for the server, the server uses a configuration similar to the hash table (hash table and might also be used) to store information.

 

But the program needs to create a session for the request of a client, the server first checks the client's request contains a session identifier - called session id, if it already contains a session id has previously been created for this client Description session, in accordance with the server session id retrieved using this session (if not retrieved, may create a new, this situation may occur on the server has deleted the session object corresponding to the user, but the user artificially in the request URL additional JSESSION back on a parameter). If the client request does not contain the session id, a session is created for this customer and this also generates a session associated with the session id, the session id is returned to the client stored in this response.

 

*************************************************************************************

XIII session id stored in several ways

*************************************************************************************

 

A. Save the session id may employ cookie, so the browser can automatically send to the server in the interactive process in accordance with the rules of the logo.

B. Since the cookie can be artificially prohibited, there must be other mechanisms in order to still be able to pass the session id in the cookie back to the server is disabled, a technique often used is called URL rewriting, the session id is appended to the URL path, additional, there are two ways, one is additional information as a URL path, the other is as a query string appended to the URL. Throughout the course of the interactive network remains the state, it must contain the session id back in the path of each client may request.

C. Another technique called the hidden form fields. That is, the server will automatically modify the form, add a hidden field to be able to pass the session id back to the server when the form is submitted.

 

*************************************************************************************

Fourteen, session is created when

*************************************************************************************

 

A common misconception is that session is created when there is client access, but the fact is being created until a server-side program call such a statement HttpServletRequest.getSession (true) only.

 

Note that the use is not displayed if the JSP <% @page session = "false"%> close the session, the JSP file compiled into Servlet automatically when the inclusion of such a statement HttpSession session = HttpServletRequest.getSession (true); this is the JSP the origins of implicit session object.

 

As the session consumes memory resources, so, if you do not intend to use the session, it should close all the JSP.

 

*************************************************************************************

Fifteen, session when it was deleted

*************************************************************************************

 

session is deleted in the following cases:

A. Program calls HttpSession.invalidate ()

B. Session id received from the last time the client sends a session interval exceeds the maximum effective time

C. The server process is stopped

 

Note that the browser is closed again only make the session cookie stored in the client browser memory failure, does not make the session object server failure, unless end just at this time Server session expiration time is up.

 

*************************************************************************************

Sixteen, URL rewrite any shortcomings

*************************************************************************************

 

Use URL rewriting of all URL, including hyperlinks, form of action, and redirect URL. Each reference your site's URL, as well as those who returned to the user a URL (even through indirect means, such as server redirects in the Location field) have to add additional information.

 

This means you can not have any static HTML pages on your site (at least not have any links to the site dynamic pages static pages). Therefore, each page must be dynamically generated servlet or JSP. Even if all the pages are dynamically generated, if the user leaves the session and back again through a bookmark or link, the session information will be lost because the store down the link identification information containing an error - the URL behind SESSION ID has expired.

 

*************************************************************************************

XVII using hidden form fields What are the disadvantages

*************************************************************************************

 

     Only when each page is generated dynamically have to submit the form, you can use this method. Click <A HREF..> conventional hypertext links do not generate form submission, therefore hidden form fields can not support a general session tracking, can only be used for a specific set of operations, such as the online store checkout process.

 

*************************************************************************************

XVIII session tracking of basic steps

*************************************************************************************

 

1. Access the session object associated with the current request

2. Find information related to the session

3. Store session information

4. Discarding data session

 

*************************************************************************************

Nineteen, getSession () / getSession (true), the difference between getSession (false) of

*************************************************************************************

 

getSession () / getSession (true): Returns the session when a session exists, or create a new session, and returns an

getSession (false): Returns the session, when the existence of the session, it would not create a new session, return null.

 

*************************************************************************************

XX, information on how to associate a session

*************************************************************************************

 

setAttribute method replaces the value set in the previous setAttribute; if you want to remove a value, without providing any substitute, you should use removeAttribute. This method triggers all valueUnbound method to achieve a value of HttpSessionBindingListener interface.

 

*************************************************************************************

XXI session attributes what type of restrictions do

*************************************************************************************

 

Type is usually as long as the session attributes Object on it. In addition to or substantially null type, such as int, double, boolean. If you are using as the attribute value of the basic type, it must be converted to the corresponding package class object.

 

*************************************************************************************

XXII, how abandoned session data

*************************************************************************************

A. I have written only removing data created by the servlet:

    Call removeAttribute ( "key") associated with the specified key value waste

B. Delete the entire conversation (in the current Web application):

    Call invalidate, the entire session is discarded. Doing so would lose all session data to the user, not just created by our servlet or JSP page session data

C. The user logs off and delete all conversations belong to him (or her) from the system

    Call logOut, customers will log off from the Web server, while discarding all sessions associated with the user (each up a Web application). This operation may affect a number of different Web applications on the server.

 

*************************************************************************************

Xxiii, isNew use to determine whether the user is the wrong practice of old and new users

*************************************************************************************

 

public boolean isNew () method if the session has not and the client (browser) the occurrence of any contact that server-side program has not yet returned to the client, then this method returns true, it usually is because the session is new, not by input customer requests caused. But if isNew returns false, just that he had previously visited Web application, it does not mean they have visited our servlet or JSP page.

 

Because the session is relevant to the user, before the user access to every page are likely to create a session. Therefore isNew to false before the user can only be accessed through the Web application, session may be the current page is created, it may be accessed by the page before the user ever created. The correct approach is to determine whether there is a session in a particular key and its value is correct. (To be tested)

 

*************************************************************************************

Twenty-four, Cookie and Session Timeout expired What is the difference

*************************************************************************************

 

Session timeout is maintained by a server, which is different from Cookie's expiration date.

 

First, the session cookie is not generally based on persistent cookie memory-resident, so there is no deadline. Even intercepted JSESSIONID cookie, and it is sent to set an expiration date. Browser session and server session will be different.

 

*************************************************************************************

XXV, lifecycle session cookie and session object is the same as you

*************************************************************************************

 

When the user closes the browser, although the session cookie is gone, but the session object still stored on the server until its expiration time.

 

*************************************************************************************

XXVI, whether as long as the browser is closed, session disappears

*************************************************************************************

 

Procedures are generally done in the user log off when issuing a command to delete the session, however, the browser will never take the initiative to inform the server to be shut down before closing, so the server will not have the opportunity to know the browser has been closed. Server will remain this session object is inactive until it is far more than a set interval.

 

The reason why there is such a misconception, because most of the session mechanism to use a session cookie to store the session id, and close your browser after the session id is gone, you can not find the connection again when the original session to the server. If the server cookie settings are saved to the hard disk, or use some means to rewrite the browser makes an HTTP request header, sending the original session id to the server, open the browser again you can still find the original session. Precisely because closing the browser does not result in session is deleted, forcing the server to set up a time to failure for the session, when more than this dead time from the time of first use session on the client, the server can assume that the client has ceased its activities, the session will be deleted to save storage space.

 

From this we can draw the following conclusions:

Close the browser, the browser is the only memory of the session cookie disappears, but does not make the session object stored in the server's disappearance, would also not have been saved to a persistent cookie on your hard drive disappeared.

 

 

Added: Then how do delete it when the browser session is closed?

 

Strictly speaking, this is not possible. Can do a little effort is to use javascript code window.oncolose in all client pages to monitor the closing action of the browser, and then send a request to remove the session to the server. But for the browser to crash or forced to kill the process of these unconventional means still powerless.

 

*************************************************************************************

Xxvii, open two browser windows to access the application will use the same session or a different session

*************************************************************************************

 

Usually session cookie can not be used across the window, when you open a new browser window into the new same page, the system will give you a new session id, the purpose of sharing information so that we can not reach the. Session is to recognize only the id does not recognize people, so different browsers, different windows open and a different cookie storage (such as a session cookie and persistent cookie) will affect the answer to this question.

 

(Tested in IE, open two browsers (not a new window, directly activated twice browser) to give the SessionID is not the same)

 

To implement session tracking across the window, we can put in the session id stored in a persistent cookie (session by setting the maximum effective time), and then read out in a new window, you can get a window on the session id, so by combined session cookie and persistent cookie, we can achieve the session tracking across the window. (To be tested)

 

*************************************************************************************

Xxviii, the number of visits each customer how to use the Session Display

*************************************************************************************

 

Since the value of customer visits is an integer variable, but the session attribute type can not be used basic types int, double, boolean variables, so we have to use these basic types of packages the type of object attributes in a session object .

 

Integer but like an immutable (the Immutable) data structure: it can not be changed after Construction. This means that each request must create a new Integer object, then use setAttribute to cover the value of the old property that existed before. E.g:

 

Integer value = (Integer)request.getSession().getAttribute("cout");

if (value == null){

     value = new CountClass (...); // create a new target can not be changed

}else{

     value = new CountClass (calculated (value)); // create a new object to the value recalculated

}

. Request.getSession () setAttribute ( "cout", value); // use the newly created object covered by the original old objects

 

*************************************************************************************

XXIX session on how to use the accumulated user data

*************************************************************************************

 

Using a variable data structure, such as arrays, List, Map or writable fields containing application specific data structure. In this way, unless the first assignment, you will not need to call setAttribute. E.g:

 

List list_check = (List) request.getSession().getAttribute("ids_go");

if(list_check = = null){

     list_check = new List(...);

     request.getSession().setAttribute(("ids_go",list_check );

}else{

      list_check .clear (); // if the object already exists is updated without resetting its properties Properties

}

List list_check1 = (List) request.getSession().getAttribute("ids_go");

System.out.println (list_check1.size ()); // this case size is 0

 

*************************************************************************************

Thirty, objects and different treatment can not be changed to change the object when the session data update

*************************************************************************************

 

Because the object can not be changed once created can not be changed, so every time you want to modify the value of the session attribute of the time, you need to call setAttribute ( "someIdentifier", newValue) instead of the original value of the property, or the value of the property does not Updated.

 

You can change the object itself because it generally provides a method to modify their properties, so every time you want to modify the value of property in the session when the relevant modify their properties to change the method just call the object on it, which means that we no need to call the setAttribute method.

Guess you like

Origin www.cnblogs.com/wzb0228/p/10974900.html