About the difference between the cookie and session

1. Since the HTTP protocol is stateless protocol, so the server need to record the user's status, you need to use some mechanism to identify specific user, this mechanism is the Session. Typical scenarios such as shopping cart, when you click on Order button, due to the stateless HTTP protocol, it does not know which user actions, so the server to be created for a specific user specific Session, with is used to identify the user, and track users, so you know inside the shopping cart there are a few books. The Session is stored on the server side, there is a unique identifier. In the process server to save a lot of Session, memory, databases, files are. When the cluster should also consider the transfer of Session, in large sites, usually have a special Session server cluster, used to store user session, this time Session information is in memory, the use of some services such as caching like Memcached to put the Session.
2. Think about how to identify specific customer service side? This time Cookie on debut. Every time the HTTP request, the client will send the corresponding information to the server Cookie. When in fact the majority of applications are used to implement Session Tracking Cookie, Session is first created, the server will tell the client in the HTTP protocol, we need to record a Session ID Cookie in which, after each request this send session ID to the server, I know who you are. Someone asked, if the client browser disabled Cookie how to do? Usually this case, URL rewriting techniques will be called using the session tracking, i.e. each HTTP interaction, URL will be a rear sid = parameters such as, the server identifies the user accordingly xxxxx attached on.
3. Cookie fact, can also be used in some user-friendly scene, imagine you had a particular landing a website, next time do not want to enter the account login again, how do? This information can be written inside Cookie, when visiting the site, Web page script can read this message, you automatically help you to fill in a user name, a user can look easy. This is also the origin of the name Cookie, a little sweetness to the user.
So, to sum up:
Session is stored in a data structure server, used to track a user's status, this data can be stored in the cluster, database, file;
Cookie is a mechanism to save the client user information is used to record some information of the user, One way is the Session.

COOKIE and SESSION What is the difference?
cookie stored in the client, session saved on the server side,
cookie purpose can track sessions, you can also save user preferences or save the username and password
session to keep track of session


① When we visit the website check to save the user name and password, the general saved are cookie, will save the user name and cookie password to the hard disk, so log in again when the browser directly to the cookie sent to the server-side validation, direct username and password saved to the client, of course, this insecurity, the browser can also do so encryption and decryption, each browser can have its own encryption and decryption way, so convenient for users, such as another user's favorite background color of the page, such as QQ background of space, this information also can be saved via a cookie to the client, then log in directly to the browser so you can get directly to the appropriate preferences.

② trace session, such as some website pages have different access rights, you can not access the pages have different levels of user access or user can log in, but the http request is stateless, each time you access the server is not known whether after the user who is logged, it is natural to think Join Login logo http request message on it, this login ID could be cookie, this cookie server you want to save have all logged-in user's cookie, so request message to the get a login ID cookie, it can be relatively long in the service side. Another example shopping site, multiple clicks to add items to the shopping cart the client it is easy to know which items in the shopping cart, but each server knows how to add items into which users log in shopping cart it? Also you need to request packet with a cookie job (without landing Jingdong also can keep adding items, suggesting that it is time to log in and send items together to create a cookie information), which are designed to track the cookie with the session , so the client has, the server there, and the server has all of the session cookie.

Behind the technology derived session, session is to use technology to the cookie, session was the result of technology, mainly for security.

http is a stateless protocol, each time a customer reads the web page, the server opens a new session, and the server does not automatically maintain client's contextual information, then how can realize online store in the shopping cart yet, session is a context-save mechanisms for information, it is for each user, the value of the variable is stored on the server side, to distinguish between different customers SessionID, session cookie or URL rewriting is based, the default use the cookie to achieve, the system will create a cookie named JSESSIONID output, we called the session cookie, in order to distinguish persistent cookies, that is, we usually refer to the cookie, attention session cookie is stored in your browser's memory and are not written to the hard disk, this is what we have just seen JSESSIONID, we usually can not see JSESSIONID love, but when we ban the cookie browser, web server will use URL rewriting way to pass Sessionid, we can see in the address bar sessionid = string to KWJHUG6JJM65HS2K6 like.

We see the last line in the HTTP request header has a cookie, but the cookie value JSessionID
Cookie: $ Version = 1; Skin = new; jsessionid = 5F4771183629C9834F8382E23BE13C4C

The first two such values, should belong to the preferences or the like.


The server is more aware of how the client's request is part of a Session it? Notes that background that jsessionid = 5F4771183629C9834F8382E23BE13C4C wood? The original is the value of Cookie HTTP request header attributes associated with the jsessionid up! (Of course, also be included with the session ID in the back of each URL rewriting oh by the way the URL).
Understand the principles, we can easily tell the difference between persistent cookies and session cookie of the online discussion on the safety of those two also clear, the session cookie for a single session, the session will end session cookie with it disappeared, and persistent cookie is only present in a piece of text on the client hard disk (usually encrypted), and may be subject to cross-site scripting and cookie spoofing attacks against cookie, of course, not as good as the security session cookie.


Usually session cookie can not be used across the window, when you open a new browser window to enter the same page, the system will give you a new sessionid, sharing information so that we can not reach the purpose, then we can put sessionid stored in persistent cookie, and then read out in a new window, you can get a window on SessionID, so by combining the session cookie and persistent cookie, we will achieve the session tracking across the window (session tracking).
In some book, web development, often simply as the Session and cookie parallel http two ways of transmitting information, session cookies on the server side, persistent cookie in the client, but they are cookie-based session, and understand links and differences between the two, we can easily select the appropriate technology to develop a web service.


Since part of the reference: session and cookie difference

=================== dividing line ==============
For example QQ space:
① when we log on QQ space , you can choose to save a user name and password so that next time you log when the browser can automatically fill or automatic landing, this time using cookie technology, will
http://qzone.qq.com/
save the cookie domain name corresponding to the hard disk , the next visit when the browser cookie filled Find corresponding to the domain name stored in the hard disk.

② After login, we may do some operations, such as deleting log, published talk, these users can only log in to do may use a cookie can also use the session session tracking

③ preference settings can be saved to the hard disk space among cookie.

-------------------------------------------------- -------------------------------------------------- ---------------------
in fact, plainly session cookie is used to save the session.
Here under the Java Servlet in the session management
http://lavasoft.blog.51cto.com/62575/275589 in-depth understanding of HTTP Session

session in web development is a very important concept, this concept is very abstract, difficult to define, is a term most people confused, and one of the most abused name, on different occasions, once the session is also very meaning Not the same. Here only discuss HTTP Session.

To illustrate the problem, here based on Java Servlet understanding of concepts and principles Session, mentioned here already covered by the JSP Servlet technology, because JSP will eventually be compiled into Servlet, the two are essentially the same.

In Java, HTTP Session object is represented by javax.servlet.http.HttpSession.

1, concepts: Session session on behalf of a server and browser, this process is continuous, it can be intermittent. In the Servlet, session refers to the object HttpSession class concept to this end, may be very vague, but only after reading this article, in order to really have a deep understanding.

2, time is created Session:
A common misconception is that session is created when there is client access, but the fact is that until a server-side program calls HttpServletRequest.getSession (true) is created when such a statement, note that if use <% @page session = "false" %> JSP not display close the session, the JSP file compiled into Servlet automatically when the inclusion of such a statement HttpSession session = HttpServletRequest.getSession (true); this is also a JSP implicit origin session object contained.
As the session consumes memory resources, so, if you do not intend to use the session, it should close all the JSP.

Extended:
1), * .html access static resources because they can not be compiled into Servlet, also does not involve the issue of the session.
2) when the JSP page does not explicitly prohibit the session, open the browser for the first time in the jsp request, the server will automatically create a session, and give it a sessionID, sent to the client browser. Then later when the client requests other resources in the present application, it will be automatically added to the request headers:
cookies: = the JSESSIONID first client session ID to get
this, when the server side receives the request, will receive session ID, and according to session objects created before the ID found in memory, provide to the requesting use. This session is the basic principle used ---- do not understand this principle, we will never understand the session.
The following are two requests for the same jsp, request headers:

FIG clearly found, when the second request, the session ID information has been added.
. 3, the time is deleted Session:
. 1) Session Timeout: Timeout refers to a continuous predetermined time server does not receive a request corresponding to the Session client, and this time exceeds the maximum time Session timeout server settings.
2) program calls HttpSession.invalidate ()
3) server is down or stop service

4, session storage Where: server memory. But session persistence management can be done through a special way.

5, session of id is coming from, how sessionID is used: when a client first request session object, the server creates a session for the client, and calculates a session ID of special algorithms, used identify the session object, when (during session continue to be valid) request other resources next browser, the browser will secretly placed the sessionID request header, after a server receives a request to get sessionID the request, the server found this session id is returned to the requestor (the Servlet) use. A session can have only one session object, session id is only recognized people do not recognize.

6, session because closing the browser and delete it?
Not, session to close only by way mentioned above.

7, the same client machine multiple requests for the same resources, the same session it?
In general, every request to create a new session.


In fact, this is not certain, summarize: For multi-label browser (such as browser 360), in a browser window, multiple tags simultaneously access a page, session one. For between multiple browser windows simultaneously or separated by a very short time a page is accessed, session is plural, and processes related to the browser. For a same browser window, directly enter different resources url to access the same application, session is the same.

8, session is a container, any object can be stored in the session.

. 9, since the session request (request object) is generated, a plurality of the same session request a shared session object may be obtained directly from the request to the session object.

10, in fact, the creation and use of the total session on the server side and the browser never get through the session object. But the browser can request Servlet (jsp also Servlet) to obtain session information. The client browser to get real tight that session ID, and this man for browser action, it is not visible, and the user need not concern ourselves in what session.
-------------------------------------------------- -------------------------------------------------
For example, following piece of code using the session
public void the doGet (the HttpServletRequest Request, the HttpServletResponse Response) throws ServletException, IOException
{

   response.setContentType("text/html");
   response.setCharacterEncoding("utf-8");
   PrintWriter out = response.getWriter();
   // 得到用户名和密码,验证
   String u = request.getParameter("username");
   String p = request.getParameter("password");

   = New new UserBeanBO UBB UserBeanBO ();
   IF (ubb.checkUser (U, P))
   {
    // 1. All the user login success information into the session
    the UserBean ubb.getUserBean UB = (U);
    Request.getSession (). the setAttribute ( "the userInfo", UB);
    // 2. extracting the information cart
    MyCartBO MCB = (MyCartBO) Request.getSession () the getAttribute ( "mycart");.    
    the ArrayList mcb.showMyCart Al = ();
    // put al placed Request
    request.setAttribute ( "mycartInfo", al);
    // valid user
    request.getRequestDispatcher ( "success.jsp") Forward (Request, Response);.
  } the else
  {
    // the user is not legitimate
      request.getRequestDispatcher ( " . the error.jsp ") Forward (Request, Response);              
  }

}

HttpSession  javax.servlet.http.HttpServletRequest.getSession()

Returns the current session associated with this request, or if the request 
does not have a session, creates one.

Returns: the HttpSession associated with this request

See Also:

getSession (boolean)
javax.servlet.http.HttpServletRequest.getSession () will return the HttpSession object associated with the current request, if does not exist, create one.

Translate, when a browser requests come, Servlet Handler (internal Servlet container implementation) will take the initiative to check whether the request for JSESSIONID information among Cookie, if so, to find the corresponding JSESSION HttpSession object, and if not, create a specific the mechanisms to achieve them Servlet container.

Original: https: //blog.csdn.net/mym940725/article/details/79159011 
 

Guess you like

Origin blog.csdn.net/weixin_41615439/article/details/87563004