1.Cookie

Client session technology to save data to the client

(I) The use of cookies

    1. Create Cookie object and bind datanew Cookie(String name, String value)
    1. Sending Cookie objectsresponse.addCookie(Cookie cookie)
    1. Get the Cookie, get the dataCookie[] request.getCookies()

(II) Details of Cookie

  1. Can I send multiple cookies at a time?
2. You can create multiple Cookie objects and call the addCookie method multiple times using Response to send cookies.Copy the code
  1. How long do cookies stay in the browser?
1. By default, when the browser is closed, the Cookie data is destroyed. * setMaxAge(int seconds) 1. Positive: Writes Cookie data to a file on the hard disk. Persistent storage. And specify the cookie survival time, when the time expires, the cookie file automatically becomes invalid. 2. Negative: the default value. 3. Zero: Deletes cookie informationCopy the code
  1. Can cookie save Chinese?
1. Before Tomcat 8, Chinese data cannot be directly stored in cookies. Chinese data needs to be transcoded -- GENERALLY using URL encoding (%E3) 2. After Tomcat 8, cookies support Chinese data. Special characters are still not supported. You are advised to use URL encoding for storage and URL decoding and parsingCopy the code
  1. Cookie sharing problem?
1. Suppose there are multiple Web projects deployed on a Tomcat server. Can cookies be shared among these Web projects? * By default, cookies cannot be shared. * setPath(String path): Sets the scope of the cookie. By default, set the current virtual directory * If you want to share, you can set the path to "/" 2. Cookie sharing problem between different Tomcat servers? * setDomain(String path): If the first level domain is set to the same, Therefore, cookies can be shared between multiple servers * setDomain(".baidu.com"), and cookies can be shared between tieba.baidu.com and news.baidu.comCopy the code
  1. What are the characteristics and functions of cookies?
The browser limits the size of a single cookie (4KB) and the total number of cookies under the same domain name (20) : 1. Cookies are generally used to store a small amount of less sensitive data. The server identifies the client without logging inCopy the code

:

Case, remember the last time you visited

  1. Example: Remember the last time you visited

    1. Requirements:

      1. Accessing a Servlet for the first time prompts: Hello, welcome to your first visit.

      2. If it is not the first time, the prompt: welcome back, your last access time is: display time string

      3. This can be done using cookies

      4. The Servlet in the server determines whether there is a cookie named lastTime

        1. Yes: Not the first visit
          1. Response data: Welcome back, you last accessed: June 10, 2018 11:50:20
          2. Write back to Cookie: lastTime= June 10, 2018 11:50:01
        2. No: first visit
          1. Response data: Hello, welcome to your first visit
          2. Write back to Cookie: lastTime= June 10, 2018 11:50:01
    2. Code implementation:

    	package cn.itcast.cookie;
    
    	import javax.servlet.ServletException;
    	import javax.servlet.annotation.WebServlet;
    	import javax.servlet.http.Cookie;
    	import javax.servlet.http.HttpServlet;
    	import javax.servlet.http.HttpServletRequest;
    	import javax.servlet.http.HttpServletResponse;
    	import java.io.IOException;
    	import java.net.URLDecoder;
    	import java.net.URLEncoder;
    	import java.text.SimpleDateFormat;
    	import java.util.Date;
    @WebServlet("/cookieTest")
    public class CookieTest extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Set the data format and encoding of the message body of the response
            response.setContentType("text/html; charset=utf-8");
    
            //1. Get all cookies
            Cookie[] cookies = request.getCookies();
            boolean flag = false;// No cookie is lastTime
            //2. Iterate over the cookie array
            if(cookies ! =null && cookies.length > 0) {for (Cookie cookie : cookies) {
                    //3. Get the name of the cookie
                    String name = cookie.getName();
                    //4. Check whether the name is lastTime
                    if("lastTime".equals(name)){
                        // There is this Cookie, not the first access
    
                        flag = true;// There is a lastTime cookie
    
                        // Set the value of the Cookie
                        // Get the current time string, reset the value of the Cookie, resend the Cookie
                        Date date  = new Date();
                        SimpleDateFormat sdf = new SimpleDateFormat("Yyyy yyyy MM dd day HH: MM :ss");
                        String str_date = sdf.format(date);
                        System.out.println("Before coding:"+str_date);
                        / / URL encoding
                        str_date = URLEncoder.encode(str_date,"utf-8");
                        System.out.println("After coding:"+str_date);
                        cookie.setValue(str_date);
                        // Sets the lifetime of the cookie
                        cookie.setMaxAge(60 * 60 * 24 * 30);/ / for a month
                        response.addCookie(cookie);
                        // Response data
                        // Get the Cookie value, time
                        String value = cookie.getValue();
                        System.out.println("Before decoding:"+value);
                        / / URL decoding:
                        value = URLDecoder.decode(value,"utf-8");
                        System.out.println("After decoding:"+value);
                        response.getWriter().write("

    Welcome back, you last visited at :"

    +value+"</h1>"); break; }}}if(cookies == null || cookies.length == 0 || flag == false) {// No, first visit // Set the value of the Cookie // Get the current time string, reset the value of the Cookie, resend the Cookie Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("Yyyy yyyy MM dd day HH: MM :ss"); String str_date = sdf.format(date); System.out.println("Before coding:"+str_date); / / URL encoding str_date = URLEncoder.encode(str_date,"utf-8"); System.out.println("After coding:"+str_date); Cookie cookie = new Cookie("lastTime",str_date); // Sets the lifetime of the cookie cookie.setMaxAge(60 * 60 * 24 * 30);/ / for a month response.addCookie(cookie); response.getWriter().write("< H1 > Hello, welcome to your first visit to "); }}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); }}Copy the code

2.Session

Server-side session technology, in which data is shared between multiple requests for a session and stored in objects on the server side

(1) Use

HttpSession = request.getSession(); 2. Use the HttpSession object:  Object getAttribute(String name) void setAttribute(String name, Object value) void removeAttribute(String name)Copy the code

(2) Details

  1. After the client is shut down but the server is not shut down, is the session obtained twice the same?

    By default. It isn't. If they need to be the same, you can create a Cookie with the key JSESSIONID, set the maximum lifetime, and keep the Cookie persistent. Cookie c = new Cookie("JSESSIONID",session.getId()); c.setMaxAge(60*60); response.addCookie(c);Copy the code
  2. The client is not closed. After the server is closed, is the session obtained twice the same?

    It's not the same, but make sure the data is not lost. Tomcat automatically implements the following tasks: Session objects are serialized to hard disks before the server is shut down. Session activation: After the server is started, session files are converted to session objects in memory. 3. When is the session destroyed? 2. The session object calls invalidate(). 3. The default session expiration time is 30 minutesCopy the code
  3. Session characteristics?

    A session can store data of any type and size. Session stores data on the server and cookies on the client. 2. There is no limit on the size of session data, but cookies have securityCopy the code