Session, Cookie Summary

Source: Internet
Author: User
Tags set cookie server memory

What is the existence of sessnion,session, how long it can save, how to set his storage time

First, what is the session

1, the session is translated into a conversation, when the client (usually the browser as a client) access to the server, if it is the first time access and reqeust.getsession () the server side can get a session object. We can call Session.getid () to get the session ID, which is the address of the session in memory on the server side.

2, if the same browser window multiple access to the server, the previous session is shared, it will not create a session, also open the window's child window, the child window and the parent window session is also shared.

Second, where the session exists

1, the session data is stored in the server side of the memory, and we get the SessionID is the session on the server side of the memory address.

2, SessionID with this sessionid each request, we will go to the server side of this memory ID to obtain the stored data. From an object-oriented perspective, he is the reference address of an object. Acquired he is the object of this session.

3, this session is generated on the server side when the client first sends the request, how do we know this sessionid the second time we visit that, there are two cases, one is the cookie is not disabled, that is, the cookie can use: When we first visit the server, the server generates a corresponding session and automatically adds the SessionID to the cookie, which is what we often see in the response message jsessionid= E377AAAA054D8F52CF7206F0A2BCEE95.TOMCAT1 So when we're on the second visit, the browser takes the information from the cookie, so we can find the session that was generated on the first visit.

Second case: Cookies are disabled: This is not the case in our first way, which means we cannot save to a cookie, so we rewrite the URL to add the Jsessionid=xxxxx value to our request path, which is the same effect as adding to the cookie. Format after URL rewrite: http://localhost:18080/servlet/index.jsp;jsessionid=93C0C1C80DC217BBDA4E78BC2377359A.tomcat1

Be aware that this is the use of '; ' instead of '? ' Linked.

Iii. how long can the session be saved?

1, the session expiration time can be set by itself, when we set the session after the session after the effective time. Even if we close the browser window the session will not expire immediately, and he still exists until his expiration date. The expiration time is the start time of the last time the server was accessed by that window, not the time it was accessed.

2. In Web. XML, we can set the expiration time for all sessions of this application:

<session-config>

<session-timeout>23</session-timeout>

</session-config>

3, set the expiration time of this session: Setmaxinactiveinterval (20); Set the time unit to seconds!

What is a cookie, where the cookie exists, and how long the value in the cookie can be stored

A. A cookie is similar to a map collection where data is stored in key=value format, and if we use a browser that does not disable cookies, the information we add to the cookie will be submitted to the server together with the requested information when the request is sent. We can obtain this cookie and the value stored in the cookie on the server side.

Second, where the cookie exists, the cookie object or the data added to the cookie is saved to the client. This is the temporary file that is saved to a disk on the client's own machine.

Third, the same as the session of the cookie we can set the validity of the cookie, and so on after the expiration of the client's amount of cookies automatically deleted.


Summary session life cycle from the Web:

The life cycle of the session

In the past when the study did not pay much attention, and today back to carefully study the life cycle of the session.

Session is stored on the server side, generally in order to prevent in the server's memory (for high-speed access), Sessinon when the user access the first access to the server created, need to be aware that only access to the JSP, servlet and other programs will be created session, only access to HTML, Static resources such as image do not create a session, and call Request.getsession (true) to force a session to be generated.

When does the session expire?

1. The server clears a session that has not been active for a long time from the server memory, and the session expires. The default expiration time for a session in Tomcat is 20 minutes.

2. Call the Invalidate method of the session.

Session requirements for the browser:

Although the session is saved on the server and is transparent to the client, it still needs the support of the client browser for its normal operation. This is because the session needs to use a cookie as the identification mark. The HTTP protocol is stateless, and the session cannot determine whether it is the same client based on an HTTP connection, so the server sends a cookie named Jsessionid to the client browser. Its value is the ID of the session (that is, the return value of Httpsession.getid ()). The session is based on the cookie to identify whether it is the same user.

The cookie is automatically generated by the server, and its MaxAge property is typically-1, which means that only the current browser is valid, and the browser windows are not shared, and the browser is disabled. Therefore, when the server is accessed by two browser windows of the same machine, two different sessions are generated. However, new windows that are opened by links, scripts, and so on in the browser window (that is, not by double-clicking on Windows that are open by desktop browser icons). Such sub-Windows share a parent window's cookie, so a session is shared.

Note: The newly opened browser window will generate a new session, except for the child window. The child window will share the session of the parent window. For example, when you right-click on a link and select Open in New window in the popup shortcut menu, the child window can access the session of the parent window.

What if the client browser disables the cookie feature or does not support cookies? For example, most mobile browsers do not support cookies. Javaweb provides another solution: URL address rewriting.

URL address Rewriting is a solution that does not support cookies for clients. The principle of URL address rewriting is to rewrite the ID information of the user session to the URL address. The server is able to parse the rewritten URL to get the session ID. This allows you to use the session to record user status even if the client does not support cookies. The HttpServletResponse class provides Encodeurl (StringUrl) Implementation of URL address rewriting, which automatically determines whether the client supports cookies. If the client supports cookies, the URL is output intact. If the client does not support cookies, the ID of the user session is rewritten into the URL.

Note: Tomcat determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, no cookie will be brought with the first request (because there is no cookie to carry), and the address after the URL address is rewritten is still jsessionid. The server has already written a cookie in the browser when the second visit is made, so the address in the URL address rewrite will not be jsessionid.

Summary cookie life cycle from the Web:

Life cycle issues with cookies

Sets the effective time of the cookie object, and the Setmaxage () method sets the time for the cookie object to be valid.

For example: cookie c = new Cookie ("username", "value"); Username is the name of this cookie and value is the one set for this cookie.

C.setmaxage (60);//60 the meaning of the second

If you do not set an expiration time, the cookie disappears when the browser window is closed as long as the cookie's lifetime is the browser session.

This cookie, which has a lifetime of browsing session, is referred to as a session cookie. Session cookies are generally not saved on the hard disk but in memory.

If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and these cookies remain valid until the set expiration time expires. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.

Cookie.setmaxage is set to 0 o'clock, the specified cookie is immediately deleted from the browser

When the cookie.setmaxage is set to-1, the representative closes the current browser and is invalidated.

Cross-domain issues from cookies on the network:

Cookie cross-domain SetDomain and SetPath

A normal cookie can only be shared in one app, meaning that a cookie can only be obtained by the app that created it.

1. The method can be shared within the same application server: Set Cookie.setpath ("/");

There are two applications for this machine Tomcat/webapp: CAs and Webapp_b,

1) The cookie that was originally set under CAS is not available under Webapp_b, and path defaults to the application that generated the cookie.

2) If you set a cookie under CAs, add a cookie.setpath ("/"), or Cookie.setpath ("/webapp_b/"), you can get the cookie set by CAS under Webapp_b.

3) The parameters here are relative to the root directory of the folder where the application server holds the application (such as WebApp under Tomcat), so Cookie.setpath ("/"), and then the cookie can be shared with all apps under the WebApp folder, The Cookie.setpath ("/webapp_b/") means that the cookie set by the CAS application is only available under the Webapp_b application, even if the CAS application that generated the cookie is not available.

4) When setting Cookie.setpath ("/webapp_b/jsp") or Cookie.setpath ("/webapp_b/jsp/"), only under webapp_b/jsp can you obtain a cookie, in Webapp_ b The cookie is not available under the JSP folder.

5) Set Cookie.setpath ("/webapp_b"), which means that cookies can be used under webapp_b so that cookies cannot be obtained under the application CAs that generate cookies.

6) There are multiple Cookie.setpath ("XXX"); When the statement is in effect, the last one will prevail.

2. How to share cookies across domains: Set Cookie.setdomain (". jszx.com");

The domain where a machine is located: Home.langchao.com,a has application CAs

The domain of B machine: Jszx.com,b has application webapp_b

1) When setting cookies under CAs, add Cookie.setdomain (". jszx.com"), so that cookies can be taken under webapp_b.

2) This parameter must be "." Begin.

3) Enter the URL to access webapp_b, you must enter the domain name in order to resolve. For example, in a machine input: http://lc-bsp.jszx.com:8080/webapp_b, can get CAs in the client set cookies, and B machine access to the application of the machine, input: http://localhost:8080/ Webapp_b are not allowed to receive cookies.

4) Cookie.setdomain (". jszx.com") is set, and can also be shared under the default home.langchao.com.


The difference and connection between the cookie and the session:

In particular, the cookie mechanism uses a scheme that maintains state on the client, while the session mechanism uses a scenario that maintains state on the server side. We also see that the session mechanism may need to use a cookie mechanism to save the identity, but in fact it has other options because the server-side hold-state scheme also needs to preserve an identity on the client side.

Cookie mechanism. Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header. However, purely client-side scripts such as JavaScript or VBScript can also generate cookies. And the use of cookies by the browser in accordance with certain principles in the background automatically sent to the server. The browser checks all stored cookies and, if a cookie declares a scope greater than or equal to the location of the resource to be requested, sends the cookie to the server on the HTTP request header of the requesting resource.

The contents of the cookie mainly include: name, value, expiration time, path and domain. The path together with the domain constitutes the scope of the cookie. If you do not set an expiration time, the cookie will be closed for the duration of the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.

Session mechanism. The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.

When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID (called the session ID.), and if it is included, it has previously created a session for this client. The server will follow SessionID to retrieve the session (not retrieved, a new one), if the client request does not include session ID, then create a session for this client and generate a SessionID associated with this session, The value of session ID should be a string that is neither duplicated nor easy to be found, and the session ID will be returned to the client in this response to save.

This session ID can be saved by using a cookie, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to SessionID. However, a cookie can be artificially banned, and there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned.

A technique that is often used is called URL rewriting, which attaches the session ID directly behind the URL path. There is also a technique called form-hidden fields. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted. Like what:

<form name= "Testform" action= "/xxx" >

<input type= "hidden" name= "Jsessionid" value= "byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764" >

<input type= "Text" >

</form>

In fact, this technique can be replaced simply by applying URL rewriting to the action.

Cookie, Session instance:

First, the cookie gets and sets, here is the demo so the value of the cookie is not encrypted and is encrypted in the actual development

Call the Request.getcookie () method to get a cookie array, we get the cookie we want through getname

Cookie[] cookies= request.getcookies ();

if (null!=cookies&&cookies.length>0) {

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

If we get the cookie we want, we get the value stored in this cookie. GetValue ()

if ("Cookie". Equals (Cookies[i].getname ())) {

SYSTEM.OUT.PRINTLN ("Cookie name" +cookies[i].getname ());

System.out.println ("Value of the Cookie" +cookies[i].getvalue ());

}else{

Create a new cookie name cookie value Hellocookie

cookiecook= New Cookie ("Cookie", "Hellocookie");

Applications under the domain name localhost domain can share this cookie

Cook.setdomain ("localhost");

This cookie can only be used by the application in this way

Cook.setpath ("/");

Cookie is valid for 60 seconds *6= 6 minutes

Cook.setmaxage (60*6);

Save this cookie to the client

Response.addcookie (Cook);

Response.sendredirect ("index.jsp");

}

}

}else{

Create a new cookie name cookie value Hellocookie

cookiecook= New Cookie ("Cookie", "Hellocookie");

Applications under the domain name localhost domain can share this cookie

Cook.setdomain ("localhost");

This cookie can only be used by the application in this way

Cook.setpath ("/");

Cookie is valid for 60 seconds *6= 6 minutes

Cook.setmaxage (60*6);

Save this cookie to the client

Response.addcookie (Cook);

Response.sendredirect ("index.jsp");

}

Second, when the cookie is disabled, our SessionID will not be automatically saved to the cookie, nor can it be saved to the cookie, so we have to rewrite the URL on the server

Protected Voiddopost (HttpServletRequest request, httpservletresponse response) Throwsservletexception, IOException {

After the cookie is used, we can use URL rewriting to submit the SessionID to the server.

Note If you disable cookies to rewrite URLs, you first get the session object, that is, to get the SessionID

Request.getsession (). SetAttribute ("Age", 10);

This is the life cycle of this session.

Request.getsession (). Setmaxinactiveinterval (20);

Call Encoderedirecturl rewrite the URL of the jump

Stringurl=response.encoderedirecturl ("index.jsp");

Output measured value rewrite URL:INDEX.JSP;JSESSIONID=3E4D0191A7850A057C164334A8997D8A.TOMCAT1

System.out.println ("Rewrite URL:" +url);

Jump

Response.sendredirect (URL);

}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Session, Cookie Summary

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.