6, Java Web Foundation (session technology -- detailed explanation of cookie s and sessions, introduction to JSP)

Keywords: Java JSP Session cookie

1, Conversation Technology

1. Concept

A session contains multiple requests and responses.

One session:
The browser sends a request to the server resource for the first time, and the session is established until one party disconnects

2. Functions:

Data is shared between multiple requests within the scope of a session

3. Method:

  • Client session Technology: cookies
  • Server side Session Technology: Session

2, Cookie s:

1. Concept:

Client session technology to save data to the client

2. Quick start:

(1) use steps:

  1. Create Cookie object and bind data
    new Cookie(String name, String value)
  2. Send Cookie object
    response.addCookie(Cookie cookie)
  3. Get cookies and get data
    Cookie[] request.getCookies()

3. Implementation principle

Implementation based on response header set cookie and request header cookie


4. cookie details

(1) can multiple cookie s be sent at a time?

sure

You can create multiple cookie objects and use response to call addCookie method multiple times to send cookies.

For example:
ServletDemo1.java

@WebServlet("/servletDemo1")
public class ServletDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c1 = new Cookie("msg","hello");
        Cookie c2 = new Cookie("code", "123456");
        //2. Send cookies
        response.addCookie(c1);
        response.addCookie(c2);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

ServletDemo2.java

@WebServlet("/servletDemo2")
public class ServletDemo2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //3. Get cookies
        Cookie[] cs = request.getCookies();
        //Get data and traverse Cookies
        if(cs != null){
            for (Cookie c : cs) {
                String name = c.getName();
                String value = c.getValue();
                response.getWriter().write(name+":"+value+",");
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

The results are as follows:

(2) how long will cookie s be saved in the browser?

① By default, when the browser is closed, the Cookie data is destroyed
② Persistent storage:

setMaxAge(int seconds)

  • Positive number: write cookie data to a file on the hard disk. Persistent storage. And specify the cookie survival time. When the time expires, the cookie file will automatically expire
  • Negative: default
  • Zero: delete cookie information

For example:

@WebServlet("/servletDemo1")
public class ServletDemo1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. Create Cookie object
        Cookie c1 = new Cookie("msg","setMaxAge");
        //2. Set the lifetime of the cookie
        //c1.setMaxAge(30);// Persist the cookie to the hard disk, and the cookie file will be automatically deleted after 30 seconds
        //c1.setMaxAge(-1);// By default, when the browser is closed, the Cookie data is destroyed
        c1.setMaxAge(0);//Delete Cookie
        //3. Send cookies
        response.addCookie(c1);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

(3) can cookie s be saved in Chinese?

  • Before tomcat 8, Chinese data cannot be stored directly in cookie s.
    *Chinese data needs to be transcoded - generally URL encoding (% E3)
  • After tomcat 8, cookie s support Chinese data. Special characters are still not supported. It is recommended to use URL encoding for storage and URL decoding and parsing

(4) cookie sharing problem?

① Suppose multiple web projects are deployed in a tomcat server, can cookie s be shared in these web projects?
  1. Cookies cannot be shared by default

  2. setPath(String path): sets the range for obtaining cookie s. By default, the current virtual directory is set
    If you want to share, you can set the path to "/"
    For example:

    @WebServlet("/servletDemo1")
    public class ServletDemo1 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //1. Create Cookie object
            Cookie c1 = new Cookie("msg","Hello");
            //Set the path so that all items deployed under the current server share Cookie information
            c1.setPath("/");
            //3. Send cookies
            response.addCookie(c1);
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    }
    
② cookie sharing between different tomcat servers?

setDomain(String path): if the primary domain name is set to be the same, cookie s can be shared among multiple servers
For example:
setDomain(".baidu.com"), then cookie s in tieba.baidu.com and news.baidu.com can be shared

5. Characteristics and functions of cookies

characteristic:

  1. Cookies store data in the client browser
  2. The browser limits the size of a single cookie (4kb) and the total number of cookies under the same domain name (20)

effect:
3. Cookies are generally used to save a small amount of less sensitive data
4. Complete the identification of the client by the server without logging in

Case 6: remember the last visit time

Requirements:
1. Access a Servlet. If it is the first time, you will be prompted: Hello, welcome to visit for the first time.
2. If it is not your first visit, you will be prompted: Welcome back. Your last visit time is: display the time string

analysis:

  1. This can be done using cookies
  2. The Servlet in the server determines whether there is a cookie named lastTime
    1. Yes: not the first visit
      1. Response data: Welcome back. Your last visit was at 11:18:54, October 3, 2021
      2. Write back Cookie: lasttime = 11:18:54, October 3, 2021
    2. No: This is the first visit
      1. Response data: Hello, welcome to visit for the first time
      2. Write back Cookie: lasttime = 11:18:54, October 3, 2021

The code is as follows:

/**
 The Servlet in the server determines whether there is a cookie named lastTime
 1. Yes: not the first visit
     1. Response data: Welcome back. Your last visit was at 11:18:54, October 3, 2021
     2. Write back Cookie: lasttime = 11:18:54, October 3, 2021
 2. No: This is the first visit
     1. Response data: Hello, welcome to visit for the first time
     2. Write back Cookie: lasttime = 11:18:54, October 3, 2021
 */
@WebServlet("/cookieDemo")
public class CookieDemo 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;//false if there is no cookie named lastTime
        //2. Traverse cookie array
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                //3. Get the name of the cookie
                String name = cookie.getName();
                //4. Judge whether the name is: lastTime
                if("lastTime".equals(name)){
                    //This Cookie is not the first visit
                    flag = true;//cookie with lastTime
                    //Response data
                    //Get the value and time of the Cookie
                    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("<h1>Welcome back. Your last visit was:"+value+"</h1>");
                    //Set the value of the Cookie
                    //Get the string of the current time, reset the value of the cookie, and resend the cookie
                    Date date  = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month dd day HH:mm:ss");
                    String str_date = sdf.format(date);
                    System.out.println("Before coding:"+str_date);
                    //URL encoding (because cookie s cannot recognize special characters such as spaces, they should be encoded and decoded with URLs)
                    str_date = URLEncoder.encode(str_date,"utf-8");
                    System.out.println("After coding:"+str_date);
                    cookie.setValue(str_date);
                    //Set cookie lifetime
                    cookie.setMaxAge(60 * 60 * 24 * 30);//one month
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        if(cookies == null || cookies.length == 0 || flag == false){
            //No, first visit
            //Set the value of the Cookie
            //Get the string of the current time, reset the value of the cookie, and resend the cookie
            Date date  = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month 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);
            //Set cookie lifetime
            cookie.setMaxAge(60 * 60 * 24 * 30);//one month
            response.addCookie(cookie);
            response.getWriter().write("<h1>Hello, welcome to visit for the first time</h1>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

The results are as follows:

be careful:
The cookie cannot parse special characters such as spaces. If it cannot be parsed, it shall be parsed with URL encoding

3, JSP: getting started

1. Concept:

Java Server Pages: java server-side pages
It can be understood as: a special page, in which both html tags and java code can be specified and defined

2. Principle

JSP is essentially a Servlet

3. Script of jsp: how JSP defines Java code

1. <% code% >: defined java code in the service method. What can be defined in the service method can be defined in the script.
2. <%! Code% >: the defined java code in the member position of the Java class after jsp conversion.
3. <% = code% >: the defined java code will be output to the page. What can be defined in the output statement can be defined in the script.

For example:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <%! int num = 5; %>
    <% System.out.println("Console print numbers:"+num);%>
    <%= "Page print number"+num %>
  </body>
</html>

The results are as follows:

4. Built in object of jsp:

(1) objects that can be used directly without obtaining and creating in jsp pages

jsp has nine built-in objects (also known as implicit objects).

(2) learn three built-in objects today:

  • request:
    The request object is an object of type javax.servlet.httpServletRequest. This object represents the request information of the client and is mainly used to accept the data transmitted to the server through HTTP protocol. (including header information, system information, request mode, request parameters, etc.). The scope of the request object is one request.
  • response:
    Response represents the response to the client, mainly passing the object processed by the JSP container back to the client. The response object also has a scope, which is only valid within a JSP page.
  • out: character output stream object. You can output data to a page. Similar to response.getWriter()

Difference between response.getWriter() and out.write():

  • Before the tomcat server actually responds to the client, it will find the response buffer data first, and then the out buffer data.
  • The data output of response.getWriter() is always before out.write()

⑶ simplify the case of remembering the last access time through JSP files

The code is as follows:

<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Page home page</title>
</head>
<body>

<%
    //1. Get all cookies
    Cookie[] cookies = request.getCookies();
    boolean flag = false;//No cookie is lastTime
    //2. Traverse cookie array
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            //3. Get the name of the cookie
            String name = cookie.getName();
            //4. Judge whether the name is: lastTime
            if ("lastTime".equals(name)) {
                //This Cookie is not the first visit
                flag = true;//cookie with lastTime
                //Set the value of the Cookie
                //Get the string of the current time, reset the value of the cookie, and resend the cookie
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month 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);
                //Set cookie lifetime
                cookie.setMaxAge(60 * 60 * 24 * 30);//one month
                response.addCookie(cookie);


                //Response data
                //Get the value and time of the Cookie
                String value = cookie.getValue();
                System.out.println("Before decoding:" + value);
                //URL decoding:
                value = URLDecoder.decode(value, "utf-8");
                System.out.println("After decoding:" + value);
%>
<h1>Welcome back. Your last visit was:<%=value%>
</h1>
<%
                break;
            }
        }
    }
    if (cookies == null || cookies.length == 0 || flag == false) {
        //No, first visit
        //Set the value of the Cookie
        //Get the string of the current time, reset the value of the cookie, and resend the cookie
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy year MM month 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);
        //Set cookie lifetime
        cookie.setMaxAge(60 * 60 * 24 * 30);//one month
        response.addCookie(cookie);

%>
<h1>Hello, welcome to visit for the first time</h1>
<span></span>
<%
    }

%>
</body>
</html>

4, Session: main course

1. Concept:

Server-side session technology shares data among multiple requests in a session and saves the data in the server-side object. HttpSession

2. Quick start:

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

For example:
SessionServlet1 sets a value for the session

@WebServlet("/sessionServlet1")
public class SessionServlet1 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Using session to share data
        //1. Get session
        HttpSession session = request.getSession();
        //2. Store data
        session.setAttribute("msg","hello session");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

sessionServlet2 gets the value in the session

@WebServlet("/sessionServlet2")
public class sessionServlet2 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //Get data using session
        //1. Get session
        HttpSession session = request.getSession();
        //2. Obtain data
        Object msg = session.getAttribute("msg");
        //Print the obtained session data to the page
        PrintWriter writer = response.getWriter();
        writer.write(msg.toString());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

The results are as follows:

3. Principle

The implementation of Session depends on cookies.

4. Details:

(1) after the client is closed, the server will not be closed. Are the two session s obtained the same?

  • By default. no
  • If you need the same, you can create a cookie with the key JSESSIONID, set the maximum survival time, and make the cookie persistent.
    Cookie c = new Cookie("JSESSIONID",session.getId());
    c.setMaxAge(60*60);
    response.addCookie(c);
    For example:
    @WebServlet("/sessionServlet1")
    	public class SessionServlet1 extends HttpServlet {
    	    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	        //1. Get session
    	        HttpSession session = request.getSession();
    	        System.out.println(session);
    	        //It is expected that the session will be the same after the client is closed
    	        Cookie c = new Cookie("JSESSIONID",session.getId());
    	        c.setMaxAge(60*60);
    	        response.addCookie(c);
    	    }
    	    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	        this.doPost(request, response);
    	    }
    	}
    

(2) if the client is not shut down and the server is shut down, are the two session s obtained the same?

Not the same, but make sure the data is not lost. tomcat does the following automatically

  • Passivation of session:
      serialize the session object to the hard disk before the server shuts down normally
  • Activation of session:
      after the server starts, convert the session file into a session object in memory.

(3) when will the session be destroyed?

  1. Server shutdown
  2. The session object calls invalidate().
  3. The default session expiration time is 30 minutes
    Selective configuration modification
    <session-config>
      <session-timeout>30</session-timeout>
    </session-config>

(4) characteristics of session

  1. Session is used to store the data of multiple requests of a session, which is stored on the server side
  2. session can store any type and size of data

(5) the difference between session and Cookie:

  1. session stores data on the server side and cookies on the client side
  2. session has no data size limit, and cookies have
  3. session data is secure, while cookies are not

(6) case: verification code

1. Case requirements:

  1. Visit the login page login.jsp with the verification code
  2. The user enters the user name, password and verification code.
    • If the user name and password are entered incorrectly, jump to the login page and prompt: the user name or password is incorrect
    • If the verification code is entered incorrectly, jump to the login page and prompt: the verification code is incorrect
    • If all inputs are correct, you will jump to the home page success.jsp and display: user name, welcome

2. Analysis

3. The effect is as follows:

4. Complete code:
Click to download the complete code

Posted by sungpeng on Sun, 03 Oct 2021 18:47:03 -0700