The following netizen answered very well

What’s the difference between cookies and sessions?

What’s the difference between cookies and sessions? The cookie is stored on the client and the session is stored on the server. The purpose of the cookie is to track the session, save user preferences or user names and passwords. Session is used to track the session

① when we log in to the website to save the username and password, generally save the cookie, the username and password of the cookie to the hard disk, so that when logging in again, the browser directly sends the cookie to the server for verification, directly save username and password to the client. Each browser can have its own encryption and decryption method, which is convenient for users. For example, the background color of the web page that users like, such as the background of QQ Space, these information can also be saved to the client through cookies. So after logging in, the direct browser can get the corresponding preferences directly.

(2) the follow-up session, such as some web pages have different access permissions, can only login user access to web pages or users of different levels can not access, but HTTP requests are stateless, every visit to the service side is do not know if the logged in user, naturally think of the HTTP request message to add login id is ok, This login id can be a cookie, such a cookie server to save the cookie of all login users, so that after the request packet comes to get the login id cookie, the server can do it for a long time. Another example is a shopping website. It is easy for the client to know which items are in the cart by clicking add to cart several times, but how does the server know which items are added to the cart of the log-in user each time? Cookie also needs to be carried in the request message (Jingdong can also continuously add goods without logging in, so it is speculated that cookies should be created and sent when logging in). These cookies are used to track the session, so the client side and the server side also have them. And the server has all session cookies.

Later,session technology is derived. Session technology uses cookies. The reason for the emergence of session technology is mainly for security.

HTTP is a stateless protocol, every time a customer reads a Web page, the server opens a new session, and the server does not automatically maintain the customer’s context information, so how to implement the shopping cart in the online store, session is a mechanism to save context information, it is for every user, Session is based on cookie or URL rewriting. The default cookie is used to implement this. The system will create an output cookie named JSESSIONID. We call it session cookies to distinguish persistent cookies, which are what we call cookies, and note that session cookies are stored in browser memory, not written to hard disk, so that’s the JSESSIONID that we saw earlier, We usually don’t see jsessionids, but when we disable cookies in the browser, the Web server passes the Sessionid as a URL rewrite, and we see strings like Sessionid =KWJHUG6JJM65HS2K6 in the address bar.

See the cookie in the last line of the HTTP request header, but it’s the cookie value of the JSessionID

Cookie: $Version=1; Skin=new; jsessionid=5F4771183629C9834F8382E23BE13C4C

The first two values, for example, should be preferences or something.

How does the server know that multiple requests from the client belong to one Session? Notice the background of the jsessionid = 5 f4771183629c9834f8382e23be13c4c yet? Jsessionid = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID = jsessionID (Of course, you can rewrite the URL to attach the session ID at the end of each URL.) After understanding the principle, we can easily distinguish between persistent cookies and session cookies, and the online discussions on the security of the two can be seen at a glance. Session cookies are for a certain session. Session cookies disappear at the end of the session, while persistent cookies are just a piece of text (usually encrypted) that exists on the client’s hard disk, and may be subject to cookie spoofing and cross-site scripting attacks against cookies. Not as secure as the session cookie.

Generally, session cookies cannot be used across Windows. When you open a new browser window to enter the same page, the system will give you a new sessionID, so that the purpose of information sharing is lost. In this case, we can first save the sessionID in the persistent cookie, and then read it in the new window, then we can get the sessionID of the previous window. In this way, session tracking can be implemented across Windows through the combination of session cookies and persistent cookies. In some web development books, Session and cookie are often simply regarded as two parallel HTTP transmission methods. Session cookies are located on the server side, while persistent cookies are located on the client side. However, session is based on cookies. Knowing the connection and difference between the two, it is not difficult to choose the appropriate technology to develop Web services.

Partly from: The difference between session and cookie

=================== ============== take an example of QQ space: ① When we log in to QQ space, you can choose to save the user name and password, so that the next login when the browser can automatically fill or automatically login, at this time the use of cookie technology, will be in

http://qzone.qq.com/

Copy the code

The cookie corresponding to the domain name is saved to the hard disk, and the browser searches for the cookie corresponding to the domain name saved in the hard disk to fill in the next access.

(2) After login, we may perform some operations, such as deleting logs and publishing, which only login users can do. We can use cookies or session tracking

③ Space preferences can be saved to the hard disk cookie.


A session is simply a cookie used to store the session. Let’s look at session management for Servlets in Java

Deep understanding of HTTP Session at http://lavasoft.blog.51cto.com/62575/275589Copy the code

Session is a very important concept in Web development. It is abstract and difficult to define. It is also one of the most confusing nouns and one of the most overused names. We will only discuss HTTP sessions here.

To illustrate, the concept and principle of Session is understood here based on Java servlets, which already cover JSP technology, because JSPS will eventually be compiled into servlets, which have the same essence.

In Java, the HTTP Session object with javax.mail. Servlet. HTTP. HttpSession.

1. Concept: Session represents a Session between the server and the browser. This Session can be continuous or intermittent. In servlets, session refers to an object of the HttpSession class, and the concept ends here. It may be vague, but it will become clear after reading this article.

Session creation time: A common misconception is that the session with the client to access when it was created, but the fact is that until a server application to call it. The getSession (true) statement to be created, <% @page session=”false”%> The JSP file is writing translated into Servlet will automatically add a statement like this HttpSession session. = it getSession (true); This is where the session object implicit in JSP comes from. Because sessions consume memory resources, you should turn them off in all JSPS if you do not intend to use them.

Static resources that access.html are not compiled into servlets, so there is no session problem. * 2), when the JSP page does not explicitly disable session, the server will automatically create a session for the first time when the browser opens the JSP request, and give it a sessionID, sent to the client browser. In the future, when the client requests other resources in the application, it will automatically add: Cookie:JSESSIONID= the session ID obtained by the client for the first time. In this way, ** server receives the session ID when receiving the request, ** finds the session object created in memory according to the ID, and provides it to the request. This is also the basic principle behind the use of sessions —- If you don’t understand this, you will never understand the principle of sessions. The following is the request header for the same JSP:

It is clear from the figure that the session ID has been added in the second request. The duration of deleting a Session is as follows: 1) Session timeout: Indicates that the server does not receive requests from the corresponding client for a period of time and the period exceeds the maximum Session timeout duration set by the server. 2) The program calls httpsession.invalidate () 3) The server is down or the service is stopped

4. Where the session is stored: in server memory. But sessions can be persisted in a special way.

Where does the session id come from and how does the sessionID work? When a client requests a session object for the first time, the server creates a session for the client and uses a special algorithm to calculate a session ID that identifies the session object. The next time the browser requests another resource (while the session is still valid), The browser surreptitiously places the sessionID in the request header. The server receives the request and gets the sessionID of the request. The server finds the session id and returns it to the requester (Servlet) for use. A session can have only one session object. For a session, only the ID is recognized, not the person.

6. Will sessions be deleted due to browser shutdown? No, sessions can only be closed in the way mentioned above.

7. Is the same session if the same client machine requests the same resource multiple times? Typically, a new session is created for each request.

In fact, this is not necessarily the case, to summarize: for multi-tab browsers (such as 360), in a browser window, multiple tabs access a page at the same time, the session is one. Sessions are multiple, depending on the browser process, for accessing a page between multiple browser Windows at the same time or within a short interval. For the same browser window, enter the URL directly to access different resources of the same application, the session is the same.

Session is a container that can store any object during a session.

9. Sessions are generated from requests (request objects). Multiple requests in the same session share a session object, which can be directly obtained from the request.

10. In fact, the session is always created and used on the server, and the browser never gets the Session object. But the browser can request servlets (JSPS are servlets too) to get session information. What the client browser is really holding on to is the session ID, which is invisible to the person doing the browser, and the user doesn’t have to care what session they’re in.

For example, the following code uses session

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

   response.setContentType("text/html");
   response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); String u = request.getParameter(String u = request.getParameter("username");
   String p = request.getParameter("password");

   UserBeanBO ubb = new UserBeanBO();
   ifUb = ubb.getUserBean(u); (ubb.checkUser(u, p)) {// 1. request.getSession().setAttribute("userInfo", ub); MyCartBO MCB = (MyCartBO)request.getSession().getAttribute()"mycart"); ArrayList al = mcb.showMyCart(); // Add al to request request.setAttribute("mycartInfo", al); / / user legal request. GetRequestDispatcher ("success.jsp").forward(request,response);
  } else{/ / the user illegal request. GetRequestDispatcher ("error.jsp").forward(request, response); }}Copy the code
HttpSession javax.servlet.http.HttpServletRequest.getSession() Returns the current session associated with this request,  orif the request 
does not have a session, creates one.

Returns: the HttpSession associated with this request

See Also:

getSession(boolean)

Copy the code

Javax.mail. Servlet. HTTP. It. GetSession () will return the HttpSession object associated the current request, if not, will create a.

When a browser request comes in, the Servlet handler (implemented inside the Servlet container) will proactively check the request Cookie for a JSESSIONID. If so, find the HttpSession object corresponding to the JSESSION. If not, create an HttpSession object. The mechanism is in the implementation of the Servlet container.

#### How do I save sessions?

Ok, no one answers, ask yourself, session is stored on the server, cookies are stored on the client. The server tracks the client by the session ID, and for the client, the session ID is saved in the cookies, so just save the cookies

json.dumps(session.cookies.get_dict())) # save
Copy the code
session.cookies.update(json.loads(f.read())) # read
Copy the code

As for whether the saved cookies are useful, THEY are useful when I write the simulated login of station B