Servlet Learning Notes (4)

Session technology Cookie and session

1. What is conversation technology?

It refers to that a user opens a browser and visits a website. As long as the browser is not closed, no matter how many hyperlinks the user clicks and how many resources the user accesses, the whole process is called a session. In a session, there can be multiple requests and data can be shared

Session tracking technologies include Cookie and Session. Cookie technology comes first

2. What’s the use of conversation technology?

When we log in to the website, some will prompt whether automatic login, so that the next visit can be directly not logged in, this is the use of session technology

3. Cookie

3.1 What is Cookie?

Cookie is a mechanism proposed by W3C and first developed by netscape community

  • I also exchanged data through HTTP protocol, but HTTP protocol is stateless. Once the data is submitted, the connection between the browser and the server will be closed, and a new connection will be created when the browser is connected again, so the server cannot wait until whether the browser came last time. As W3C has proposed, each user is given a pass, and whoever accesses it carries the pass, so that the server can access the user’s information
3.2 using cookies

==Cookie is implemented based on the response header set-cookie and request header Cookie

** Browsers have limits on the size of individual cookies (4KB) **

Add a Cookie

// Set the encoding of response
response.setContentType("text/html; charset=utf-8");
// Create a Cookie object
Cookie cookie = new Cookie("username"."linzeliang");
// Set the cookie's maxAge expiration time to 1 hour
cookie.setMaxAge(60 * 60)
// Add the cookie object to the Response object and send the cookie
response.addCookie(cookie);
Copy the code

To get a Cookie

// Get the Cookie sent by the browser via request
Cookie[] cookies = request.getCookies();
// Iterate through the cookies to get each cookie
for (Cookie cookie : cookies) {
    System.out.println(cookie.getValue());
}
Copy the code

Cookie workflow:

  • The browser visits the server. If the server needs to record the status of the user, it sends a Cookie to the browser using Response, and the browser saves the Cookie. When the browser visits the server again, the browser sends the requested URL to the server along with the Cookie.

Cookie API:

  • The Cookie class creates a Cookie object
  • The Response interface defines an addCookie method, which is used to add a corresponding set-cookie header field to its response header
  • The request interface defines a getCookies method, which is used to getCookies submitted by the client

Common Cookie methods:

  • public Cookie(String name,String value)
  • SetValue and getValue methods
  • SetMaxAge and getMaxAge methods
  • SetPath and getPath methods
  • SetDomain and getDomain methods
  • GetName method
3.2 Can I create multiple cookies?

You can. You can send multiple cookies by calling the addCookie method multiple times, and the browser will receive multiple cookies

3.3 How long does the Cookie stay in the browser?
  • By default, cookies are destroyed when the browser is closed
  • If you want persistent storage, that is, to be stored on hard disk, you need to set it up on the serverresponse.setMaxAge(int seconds):
    • If seconds is an integer, the number represents how many seconds are stored
    • If it is negative (the default is -1), it means that the Cookie is temporary. Close the browser and destroy the Cookie immediately
    • If the value is 0, it indicates that the Cookie information is deleted. That is, the next time the browser requests the client, the Cookie is not carried because it has been deleted
3.4 Cookie is saved in Chinese
  • Prior to Tomcat8, cookies could not save Chinese and needed to urL-encode Chinese

    Cookie cookie = new Cookie("username", URLEncoder.encode("Name"."UTF-8"));
    // Similarly, even if the cookie is sent to the browser through the URL encoding, the browser is also stored in the disk according to the URL encoding, and we need to decode it when we get the cookie
    Cookie[] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
        String name = cookie.getValue();
        / / URLDecoder decoding
        String value = URLDecoder.decode(name, "UTF-8");
        System.out.println(value);
    }
    Copy the code
  • In Tomcat8 and later, cookies support Chinese data, but still do not support special characters. For easy maintenance, it is recommended to use URL encoding for storage and parsing

3.5 Cookie’s non-transdomainability

Does the browser take all the cookies to the server when accessing the Servlet, or does it change the cookies of other sites? No, cookies are not cross-domain. The browser determines whether a web site can handle another web site’s cookies based on the domain name. Therefore, generally speaking, when I visit Baidu, the browser will only bring the Cookie issued by Baidu instead of Google’s Cookie

3.6 Modifying or Deleting the Cookie Value

Cookie mechanism also does not provide a way to modify cookies, so how do we change the value of cookies?

We can pass cookies with the same name. Add response to the browser, which overwrites the Cookie

Cookie delete color map Max Age change to 0

Note: When deleting or modifying a Cookie, all attributes of the new Cookie except value and maxAge must be the same as the original Cookie. Otherwise, the browser will regard the Cookie as different and will not overwrite it, resulting in deletion and modification failure!

3.7 Cookie Sharing

Normal cookies can only be shared within one application, that is, a cookie can only be obtained by the application that created it.

  1. By default, multiple Web projects are deployed on a Tomcat server, so cookies cannot be shared in these Web projects. If you need to share cookies, you only need to set setPath(“/”), because the default is the current virtual directory (“/” refers to the relative path, in this case, the application deployment path. Tomcat/webapp)

    When you set cookie.setPath(“/ webapp_A/JSP “) or cookie.setPath(“/webapp_a/ JSP /”), you can only get cookies under webapp_a/ JSP Cookies are not available for those under WebApp_A but outside the JSP folder

  2. Cookie sharing problem between different Tomcat servers

    The domain property of the Cookie determines the domain name to run the access Cookie. Domain is set to. Domain name.

    • The privacy security mechanism of cookies determines that cookies are not cross-domain. In other words, the cookies between www.baidu.com and www.google.com are not exchanged. Even if the same level 1 domain name, different level 2 domain names cannot be exchanged, that is, the cookies of www.goole.com and www.image.goole.com cannot be accessed

    • Now if I want the same level 1 domain name of the web page cookies can access each other. In other words, if www.img.linzeliang.com can obtain the Cookie of www.linzeliang.com, it needs to use the domain method

      Cookie cookie = new Cookie("username"."linzeliang");
      cookie.setMaxAge(60 * 60);
      cookie.setDomain(".linzeliang.com");
      response.addCookie(cookie);
      Copy the code
  3. SetPath () and setDomain() differ:

    • The setDomain() in cookies is used on two sites with different names but the same suffix (different hosts) so that both sites can use the same Cookie
    • SetPath () is mainly used to determine which suffix can use the cookie, i.e., the address constraint above the address bar
3.8 Security attributes of cookies

HTTP is not only stateless, but also insecure because it is transmitted in plain text. If you do not want cookies to be transmitted over insecure protocols, you can set the secure property of cookies to true, so that the browser will only transmit the cookies over secure protocols such as HTTPS and SSL

3.9 Cookie application

Displays the last access time of the user

  • If the user logs in for the first time, the time is recorded, the Cookie is sent, and the user logs in for the first time when the page is printed; If not the first time, when was the last time you logged in

  • The code is as follows:

    response.setContentType("text/html; charset=utf-8");
    // Get all cookies sent by the browser
    Cookie[] cookies = request.getCookies();
    // Use it to determine whether access has been made
    boolean flag = false;
    if(cookies ! =null&& cookies.length ! =0) {
        for (Cookie cookie : cookies) {
            if ("lastTime".equals(cookie.getName())) {
                // The tag has been accessed
                flag = true;
                // Get the last login record
                String dateValue = cookie.getValue();
                dateValue = URLDecoder.decode(dateValue, "utf-8");
                PrintWriter pw = response.getWriter();
                // Display to the browser
                pw.write("
            

    Hello, you last logged in at"

    + dateValue + "</h1></center>"); // Get the time record of this visit Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("Yyyy yyyy MM dd day HH: MM :ss"); String str_date = sdf.format(date); str_date = URLEncoder.encode(str_date, "utf-8"); cookie.setValue(str_date); cookie.setMaxAge(60*60*24*30); // Send a new Cookie to override the original Cookie response.addCookie(cookie); break; }}}// First visit if (cookies == null || cookies.length == 0 || flag == false) { Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("Yyyy yyyy MM dd day HH: MM :ss"); String str_date = sdf.format(date); // Use URL encoding, otherwise the space browser will not parse str_date = URLEncoder.encode(str_date, "utf-8"); Cookie cookie = new Cookie("lastTime", str_date); cookie.setMaxAge(60*60*24*30); response.addCookie(cookie); } Copy the code

4.Session

4.1 What is Session?

Session Server-side Session technology, which shares data between multiple requests for a Session, stores the data in a server-side object, corresponding to the HttpSession object

Session is another mechanism for logging browser state. The difference is that cookies are stored in the browser and sessions are stored in the server. When a user accesses a server using a browser, the server records the user’s information in a form called a Session

Whereas a Cookie checks the user’s “pass” to confirm the user’s identity, a Session checks the server’s “customer list” to confirm the user’s identity. A Session creates a “customer list” in the server

Why do we have sessions when we have cookies?

Session is easier to use than Cookie. It can solve things that cookies can’t solve (Session can store objects, Cookie can only store strings)

4.2 use Session

Getting the Session object

// Get the session object
HttpSession session = request.getSession();
// Set the session attribute
session.setAttribute("username"."linzeliang");
Copy the code

Access the Session object Settings from other servlets

HttpSession session = request.getSession();
String value = (String) session.getAttribute("username");
System.out.println(value);
// The result of printing is Linzeliang
Copy the code

In general, we use Session when we want to store user-level data, but what is user-level? As long as the browser is open and the data is expected to remain, use Session to save it.

Session API

  • long getCreationTime(); Get the time when the Session was created
  • String getId(); [Get Session ID]
  • long getLastAccessedTime(); Return the last active time of Session
  • ServletContext getServletContext(); Get the ServletContext object
  • void setMaxInactiveInterval(int var1); [Setting Session timeout]
  • int getMaxInactiveInterval(); [Obtain Session timeout]
  • Object getAttribute(String var1); [Obtain Session attribute]
  • Enumeration getAttributeNames(); Get all Session attribute names
  • void setAttribute(String var1, Object var2); [Setting Session attributes]
  • void removeAttribute(String var1); [Remove Session attribute]
  • void invalidate(); [Destroy Session]
  • boolean isNew(); [Whether the Session is new]
4.3 After the Client is Shut down but the server is not shut down, Is the session obtained twice the same?
  • JSESSIONID is automatically sent, but setMaxAge is the default. If you close the browser, cookies will be lost, so you can’t find the original session by ID.

  • If you want to be the same, you can create a Cookie with a JSESSIONID key. Set the setMaxAge

    Cookie c = new Cookie("JSESSIONID", session.getId());
    c.setMaxAge(60 * 60);
    response.addCookie(c);
    Copy the code
4.4 If the Client Is Not Shut Down and the Server is Shut down, Is the Session Obtained twice the Same?
  • Not the same, but to ensure data is not lost, Tomcat automatically performs the following operations:
    • Session passivation:
      • Serialize the Session object to hard disk before the server is properly shut down
    • Session activation:
      • After the server starts, the session file is converted to the session object (although the object is not the same, the data is the same).
4.3 When is the session destroyed?
  1. The server is shut down.

  2. The session object calls the invalidate() method to invalidate many attributes in the session, often used for safe exit

  3. The default value is 30 minutes. If tomcat’s web. XML conflicts with your own web application’s web.

    <session-config>    <session-timeout>60(custom time, default 30)</session-timeout></session-config>
    Copy the code
  4. Run the setMaxInactiveInterval() method

    / / set the Session timeout for 60 seconds, longest Session. Here is the unit of seconds setMaxInactiveInterval (60); System.out.println(session.getMaxInactiveInterval());
    Copy the code
4.4 The validity period of Session and Cookie are different
  1. The session:
    • The duration of a session is how long it has not been accessed
    • If you want a session attribute to be invalidated, you can use the removeAttribute() method
  2. Cookies:
    • The Cookie cycle is timed from the time the Cookie arrives in the user’s memory, regardless of whether it was accessed or not
4.5 What If Cookies are Disabled?

Since sessions run on cookies, what happens to sessions if cookies are disabled?

  • We can rewrite the URL, HttpServletResponse encodeURL(String URL) encodeRedirectURL(String url)tring URL) encodeRedirectURL(String url) Use sendRedirect to redirect so that the JSESSIONID is carried through the URL
  • Principle of URL address rewriting: The Session ID is rewritten to the URL address. The server parses the rewritten URL to obtain the Session ID. This way, even if cookies are disabled by the browser, the Session ID is passed through the server and the Session can still be used to record the user’s state


EncodeURL (java.lang.string URL) The implementation mechanism of this method is as follows:

  • Check whether Session is enabled for the current Web component. If Session is not enabled, return the url.
  • Then check whether the client browser supports Cookie. If Cookie is supported, the parameter URL is returned directly. If cookies are not supported, add Session ID information to the parameter URL and return the modified URL.
4.5 Disabling Cookies for Sessions (Making Sessions independent of Cookies)

The Java Web specification supports disabling cookies by configuring them to disable cookies for your own projects in the context.xml file in the meta-INF folder.

To disable cookies for all Web applications, go to conf/context.xml

== Note == : this configuration only prevents the server from automatically maintaining cookies named jsessionID, and does not prevent cookies from being read or written

4.8 Characteristics of Session
  • Session is used to store the data of multiple requests for a session and is stored on the server
  • Sessions can store data of any type and size
4.9 Differences between Session and Cookie

Compare from storage mode

  • Cookies can only store strings, and if you want to store non-ASCII strings, you have to encode them
  1. There is no limit on the size of the session, and the maximum size of the cookie is 4KB (4095-4097B).
  • Session storage data is secure, while cookie storage data is insecure

  • A Session can store any type of data. You can think of a Session as a container

Compare from privacy security

  • Cookies are stored in the browser and are visible to the client. Information is easy to leak out. If you use cookies, it is best to encrypt them
  • Sessions are stored on the server and are transparent to clients. There is no sensitive information leakage problem.

From the period of validity

  • Cookies are stored on the hard disk. You only need to set the maxAge property to a large positive integer. Cookies will still exist even if the browser is closed
  • Sessions are saved on the server. Set the maxInactiveInterval value to determine the Session validity period. And the Session relies on a Cookie named JSESSIONID, whose default maxAge attribute is -1. If the browser is closed, the Session is invalidated, though not extinguished from the server.

Compare the load from the server

  • Sessions are stored on the server. Each user generates a Session. If a large number of concurrent users access the server, sessions cannot be used because they consume a large amount of memory.
  • Cookies are stored on the client. Does not occupy server resources. Large websites such as Baidu and Sina generally use cookies for session tracking.

Compare from browser support

  • Cookies are useless if the browser disables them
  • If cookies are disabled by the browser, sessions can be traced by URL rewriting.

Compare across domains

  • Cookie can set the domain property to implement cross-domain
  • Session is valid only for the current domain name