Introduction to Servlet foundation - Introduction to session Technology

Posted by Ron Woolley on Wed, 27 Oct 2021 17:22:13 +0200

Introduction to Servlet foundation - Introduction to session Technology

1. Introduction to conversation Technology

1.1 overview of conversation Technology

1.1.1 what is conversation

    Session means that a user opens a browser and accesses a website. As long as the browser is not closed, no matter how many hyperlinks the user clicks and how many resources he accesses, until the user closes the browser, the whole process is called a session.

    Why do we use conversation technology?

    Here are the five features of the HTTP protocol of the other two knowledge points of schenkorp:

    1) Simple and fast; 2) Flexibility; 3) No connection; 4) Stateless; 5) Support B/S and C/S modes.

1.1.2 what is connectionless

    No connection: it restricts only one request per connection. After the server processes the customer's request and receives the customer's response, it disconnects. In this way, the transmission time can be saved.

    We know that short connections are used by default in HTTP/1.0. In other words, every time the client and server perform an HTTP operation, a connection is established, and the connection is interrupted at the end of the task. The reason for doing so in the early stage is that the data exchange between each client (i.e. browser) and the server is intermittent. If the application or upper layer protocol does not send data all the time, or sends data every long time, most channels will actually be idle and occupy resources for no reason. Therefore, the designers of HTTP intend to use this feature to design the protocol to establish a connection when requesting and release the connection after requesting, so as to release resources to serve other clients as soon as possible. The advantage of this is that it can greatly reduce the pressure on the server.

     But over time, Web pages become more and more complex. Usually, a Web page may have many components. In addition to the text content, it also has static resources such as js, css, pictures and so on. If you encounter such a Web resource, the browser will re-establish a TCP connection, initiate an HTTP request, and then close it, which is very inefficient. Later, keep alive was proposed to solve the problem of low efficiency.

    From HTTP/1.1, the long connection is used by default (keep alive is enabled by default). When a web page is opened, the TCP connection between the client and the server for transmitting HTTP data will not be closed. When the client accesses the server again, it will continue to use the established connection. Keep alive will not keep the connection permanently. In general, the connection reuse mechanism of keep alive in HTTP protocol is mainly controlled by the server.

1.1.3 what is stateless

    Stateless: refers to that the protocol has no memory ability for transaction processing. Missing status means that if the previous information is required for subsequent processing, it must be retransmitted, which may increase the amount of data transmitted per connection. However, when the server does not need previous information, its response is faster.

      HTTP was not designed to save session state. No matter what web pages you have visited and what data you have submitted, the web pages you have obtained are the same; Different browsers visit the same web page and get exactly the same results. This is called "statelessness" -- the result of accessing the URI is irrelevant to the context operation and the user.

1.1.4 why use session technology

    We learned earlier that HTTP does not save the session state and does not care about the whole context operation. In the face of increasingly complex web applications, it is inevitable that there are some relationships between pages, pages and users.

    For example, case 1: after A and B log in to an account on A shopping website, A and B want to know A/B's preferences through Servlet_Look, click A detail link, which is A thunder snake mouse, and B also passes through the Servlet_Look, click A detail link, which is A mechanical keyboard. All this information will be saved, but this Servlet_Look doesn't know who's looking. Now, what if you want to save this information?

    Think about it: can we use the HttpServletRequest we learned before   Object and ServletContext object to save this data?

    The answer is: No.

    Reason why HttpServletRequest cannot be used: there are multiple requests and responses in one session, and each request from the browser client will generate an HttpServletRequest object, which will only save the information of this request. Previously saved information will be lost.

     Reasons why ServletContext cannot be used: ServletContext objects are shared by the whole web application. Storing data here will undoubtedly fail to distinguish the ownership of specific information. Is it A or B?

    For example, case 2: A requests A servlet on his own computer through IE browser_ Login entered the shopping website landing page and successfully logged in. The next day, A asked for servlet through IE browser on his computer_ Login. At this time, the server does not know who initiated the HTTP request, and the business HTTP request will not identify who initiated it. So, A has to enter the user name and password again.

    In view of this situation, how does the server save this information? It is really troublesome to bind clients and users. What if it is used by others? What if you change the client?

    Therefore, session tracking technology came into being, one is cookie and the other is session. Session tracking technology can solve many of our problems.

1.2 Cookie Technology

1.2.1 what is a Cookie

    Cookie is a mechanism proposed by W3C and first developed by netscape community. The interaction between web pages transmits data through HTTP protocol, while HTTP protocol is a stateless protocol. The server can not determine the user information, so W3C proposed that each user should be issued a pass, and whoever accesses should carry the pass, so that the server can confirm the user's information from the pass. The pass is a cookie (generally, the size of a cookie is limited to 4k).

    Cookie is a client technology. The server writes each user's data to their respective browser in the form of cookie. When the user uses the browser to access the web resources in the server, the browser will give the requested URL to the server together with the cookie. In this way, web resources deal with the data of users.

1.2.2 common API s for cookies

methodexplain
response.addCookie(Cookie cookie)Add Cookie to client
Cookie cookies[]=request.getCookies();Read cookies
Cookie(String name, String value)Construct a cookie containing the specified name and value
getValue()Returns the value of the cookie
setValue(String newValue)A cookie created after assigning a new value to a cookie
setMaxAge(int expiry)Sets the lifetime of the cookie, specified in seconds
getPath()Return this cookie in the server path
setPath(String uri)Specify a path to the client cookie that should return the cookie
getDomain()Returns the domain name set by this cookie
getName()Returns the name of the cookie

1.2.3. Creating and reading cookies

Use case:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServletDemo1 extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  response.setContentType("text/html;charset=gbk");
	      PrintWriter out = response.getWriter();
	      //Create Cookie
	      Cookie cookie=new Cookie("name","Mu Jinxuan");
	      //Set the cookie life cycle: if MaxAge is a positive number, the browser will write the cookie to the hard disk
          //MaxAge is a negative number. The Cookie is temporary and only valid in this browser. If you close the browser, the Cookie will become invalid
          //If MaxAge is 0, the Cookie is deleted
	      cookie.setMaxAge(3600);
	      //Write cookie information back to the browser
	      response.addCookie(cookie);
	      out.println("<form action='/CookieServletDemo1' method='post' >");
	      out.println("<input type='submit' value='establish Cookie' /><br />");
	      out.println("</form><br />");
	      out.flush();
	      out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=gbk");
		//Read cookie information
	    Cookie cookies[]=request.getCookies();
	    PrintWriter out = response.getWriter();
	    for(int i=0;i<cookies.length;i++){
	         Cookie cookie=cookies[i];
	         out.println(cookie.getName()+"="+cookie.getValue());
	         out.println("Life cycle:"+cookie.getMaxAge());
	    }
	    out.flush();
	    out.close();
	}
}

Case effect:

 

    google will write Cookies to the Cookies file. IE will generate a separate file and save the corresponding Cookie. If the stored Cookie has the same key, it will be overwritten.

1.2.4 Cookie life cycle and effective path

    The life cycle of a cookie can be through cookie.setMaxAge (seconds). If setMaxAge is not set, the life cycle of the cookie will die when the browser is closed;

Cookie.setmaxage (seconds):

    A positive number indicates that it expires after the specified number of seconds;

    A negative number indicates that the Cookie will be deleted as soon as the browser is closed (the default value is - 1).

    0 indicates that the Cookie will be deleted immediately.

    The path attribute of cookies can effectively filter which cookies can be sent to the server and which are not sent.

Use case:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServletDemo2 extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  response.setContentType("text/html;charset=gbk");
	      PrintWriter out = response.getWriter();
	      
	      //Create Cookie: added the first time / cookie servletdemo2 is accessed
	      Cookie cookie=new Cookie("name","Mu Jinxuan");
	      //Set the life cycle of cookie s
	      cookie.setMaxAge(3600);
	      
	      //Create Cookie2: if it is added when accessing / CookieServletDemo3
	      Cookie cookie2=new Cookie("name2","Mu Jinxuan 2");
	      //Set the lifecycle of cookie2
	      cookie2.setMaxAge(3600);
	      cookie2.setPath("/CookieServletDemo3");
	      
	      //Write cookie information back to the browser
	      response.addCookie(cookie);
	      response.addCookie(cookie2);
	      out.println("<form action='/CookieServletDemo2' method='post' >");
	      out.println("<input type='submit' value='establish Cookie' /><br />");
	      out.println("</form><br />");
	      out.flush();
	      out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=gbk");
		//Read cookie information
	    Cookie cookies[]=request.getCookies();
	    PrintWriter out = response.getWriter();
	    for(int i=0;i<cookies.length;i++){
	         Cookie cookie=cookies[i];
	         out.println(cookie.getName()+"="+cookie.getValue());
	         out.println("Life cycle:"+cookie.getMaxAge());
	    }
	    
	    //Create Cookie3: if it is added when accessing / CookieServletDemo2
	    Cookie cookie3=new Cookie("name3","Mu Jinxuan 3");
	    //Set the life cycle of cookie3
	    cookie3.setMaxAge(3600);
	    cookie3.setPath("/CookieServletDemo2");
	    response.addCookie(cookie3);
	    
	    out.flush();
	    out.close();
	}
}

Case effect:

     In the above case: when I visit http://localhost:8080/CookieServletDemo2 cookie2 was not added.

1.2.5 domain name of Cookie

    When we learn JavaScript, JavaScript does not allow cross domain calls to objects on other pages for security reasons (due to the limitation of homology Policy). Similarly, the privacy security mechanism of cookies determines that cookies cannot cross domains. The simple understanding is that Cookie objects between different URL s are inaccessible.

    When we visit websites, many of us have the concept of domain name for convenience of memory. The domain name will eventually be translated into the corresponding IP address. The first thing to look for is our hosts file. If not, we will get it from the DNS domain name system.

The premise of this case:

    1) Locate the hosts file in the path C:\Windows\System32\drivers\etc

    Configure the mapping relationship between the following domain name and IP:

    127.0.0.1 localhost ​

    127.0.0.1 www.mjx.com

Use case:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieServletDemo3 extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  response.setContentType("text/html;charset=gbk");
	      PrintWriter out = response.getWriter();
	      
	      //Create Cookie: added the first time / cookie servletdemo2 is accessed
	      Cookie cookie=new Cookie("name","Mu Jinxuan from_www.mjx.com");
	      //Set the life cycle of cookie s
	      cookie.setMaxAge(3600);
	      //Write cookie information back to the browser
	      response.addCookie(cookie);
	      out.println("<form action='/CookieServletDemo3' method='post' >");
	      out.println("<input type='submit' value='establish Cookie' /><br />");
	      out.println("</form><br />");
	      out.flush();
	      out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=gbk");
		//Read cookie information
	    Cookie cookies[]=request.getCookies();
	    PrintWriter out = response.getWriter();
	    for(int i=0;i<cookies.length;i++){
	         Cookie cookie=cookies[i];
	         out.println(cookie.getName()+"="+cookie.getValue());
	         out.println("Life cycle:"+cookie.getMaxAge());
	    }
	    out.flush();
	    out.close();
	}
}

Case effect:

      We see that the Domain field is our Domain name, and cookies between different Domain names are not shared.

1.3. session Technology

1.3.1 what is a session

    I learned earlier that Cookie is a client-side technology and session is a server-side technology. It is another mechanism to record browser status. Using this technology, the server can create an exclusive session object for each user's browser when running. Because the session is exclusive to the user's browser, users can put their own data in their own session when accessing the server's web resources. When users access other web resources in the server again, Other web resources then take data from the user's own session to serve the user.

    Why session? Session is easier to use than cookies. Session can solve things that cannot be solved by cookies. Session can store objects, and cookies can only store strings. Session can be regarded as a container class, similar to HashMap.

    What session can be used to do: store shopping carts in online shopping malls, save login user information, prevent users from illegally logging into a page, and so on.

1.3.2 common session API s

methoddescribe
long getCreationTime();Gets the time when the Session was created
String getId();Get Session id
long getLastAccessedTime();Returns the last active time of the Session
ServletContext getServletContext();Get ServletContext object
void setMaxInactiveInterval(int var1);Set Session timeout
int getMaxInactiveInterval();Get Session timeout
Object getAttribute(String var1);Get Session property
Enumeration getAttributeNames();Gets all the attribute names of the Session
void setAttribute(String var1, Object var2);Set Session property
void removeAttribute(String var1);Remove Session property
void invalidate();Destroy the Session
boolean isNew();Is the Session new

1.3.3. Create / read / delete Session

1) Get session:

    HttpSession session=request.getSession();

    Note: session is stored in the memory of the server. A user browser exclusively enjoys a session domain object. This method is equivalent to request.getSession(true) to obtain a session. If not, a new session will be created. Of course, there is also request.getSession(false) to obtain the session. If not, it will not be created.

2) Get the session ID

    session.getId()

    Sessionid is the key of a session. When the browser accesses the server for the first time, it will generate a session on the server side, with a sessionid corresponding to it. The session ID generated by tomcat is called jssessionid.

    The ManagerBase class of tomcat provides the method of creating sessionid: random number + time + jvmid;

    The client only saves the sessionid to the cookie, not the session. The properties of the session object are saved in the memory of the server.

2) Add properties to session

    session.setAttribute(String name, Object val);

3) Get properties from session

    String name=(String) session.getAttribute(String name);

4) Remove properties from session

    session.removeAttribute("username");

1.3.4. Session life cycle and validity period

The default lifetime of a session is 30 minutes.

1) Set Session timeout

    a) Method 1: modify the configuration in tomcat/conf/web.xml

<!--Find this configuration: the default is 30 minutes, and the timeout is modified to 20 minutes-->
<session-config>           
    <session-timeout>20</session-timeout>            
</session-config>

    b) Method 2: add a new configuration in the web.xml of a single web application

    c) Method 3: set separately in the program: setmaxinactivitinterval (int VAR1);

    Is the timeout length (in seconds); A negative number means never timeout.  

2)getMaxInactiveInterval();

    Gets the timeout of the Session.

    Note: the timeout of Session is the time period from the last access time to the next access. If the time period exceeds the timeout, the Session will be removed from memory.

3)invalidate();

    Make the current Session timeout invalid immediately.

    Note: the timeout is invalid. The Session id will not be deleted, but the Session object cannot obtain the Session property.

Use case:

1) Create a new SessionDemo

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SessionDemo extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  response.setContentType("text/html;charset=gbk");
		  PrintWriter out = response.getWriter();
	      out.println("<body>");
	      out.println("<iframe name='target' width='500' height='300' style='float: left;'></iframe>");
	      out.println("<div style='float: left;'>");
	      out.println("<ul style='list-style: none;'>");
	      out.println("<li><a href='/SessionDemo2?action=isNew' target='target'>Session Creation and acquisition of( id (No. and whether it is newly created)</a></li>");
	      out.println("<li><a href='/SessionDemo2?action=setAttribute' target='target'>Session Storage of domain data</a></li>");
	      out.println("<li><a href='/SessionDemo2?action=getAttribute' target='target'>Session Acquisition of domain data</a></li>");		
	      out.println("<li>Session Survival of</li>");
	      out.println("<li>");
	      out.println("<ul style='list-style: none;'>");
	      out.println("<li><a href='/SessionDemo2?action=getMaxInactiveInterval' target='target'>obtain Session Timeout data for</a></li>");
	      out.println("<li><a href='/SessionDemo2?action=defaultLife' target='target'>Session Default timeout and configuration</a></li>");
	      out.println("<li><a href='/SessionDemo2?action=lifeNew' target='target'>Session3 Seconds timeout destroy</a></li>");
	      out.println("<li><a href='/SessionDemo2?deleteNow=isNew' target='target'>Session Destroy it now</a></li>");
	      out.println("</ul>");
	      out.println("</li>");
	      out.println("</ul>");
	      out.println("</div>");
	      out.println("</body>");
	      out.flush();
	      out.close();
	}
}

2) Create a new SessionDemo2 and configure web.xml

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionDemo2 extends HttpServlet{
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String action = request.getParameter("action");
		System.out.println(action);
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=gbk");
		if("isNew".equals(request.getParameter("action"))) {
			 // Create and get Session object: equivalent to request.getSession(true)
	        HttpSession session = request.getSession();
	        // Judge whether the current Session is newly created
	        boolean isNew = session.isNew();
	        // Get the unique id of the Session session: this id is created by the server: random number + time + jvmid
	        String id = session.getId();
	        response.getWriter().write("Get Session,its id Yes:" + id + " <br /> ");
	        response.getWriter().write("this Session Is it newly created:" + isNew + " <br /> ");
		}else if("getAttribute".equals(request.getParameter("action"))) {
			Object attribute = request.getSession().getAttribute("key1");
			response.getWriter().write("from Session Get out of key1 The data are:" + attribute);
		}else if("setAttribute".equals(request.getParameter("action"))) {
			request.getSession().setAttribute("key1", "value1");
			response.getWriter().write("Already gone Session Data saved in");
		}else if("deleteNow".equals(request.getParameter("action"))) {
			 // Get the Session object first
	        HttpSession session = request.getSession();
	        // Let the Session timeout immediately: timeout does not remove the sessionid
	        session.invalidate();
	        response.getWriter().write("Session Has been set to timeout (invalid)");
		}else if("defaultLife".equals(request.getParameter("action"))) {
			// Gets the default timeout of the Session
	        int maxInactiveInterval = request.getSession().getMaxInactiveInterval();
	        response.getWriter().write("Session The default timeout for is:" + maxInactiveInterval + " second ");
		}else if("lifeNew".equals(request.getParameter("action"))) {
			// Get the Session object first
	        HttpSession session = request.getSession();
	        // Set the timeout after 3 seconds for the current session
	        session.setMaxInactiveInterval(3);
	        response.getWriter().write("current Session Has been set to timeout after 3 seconds");
		}else if("getMaxInactiveInterval".equals(request.getParameter("action"))) {
			// Get the Session object first
	        HttpSession session = request.getSession();
	        response.getWriter().write("current Session The timeout for is:"+session.getMaxInactiveInterval());
		}
	}
}

Case effect:

    If you change the browser, you can also get a session ID. Why can the server provide different sessions for different browsers?

    Because when each browser visits the web site, if the http request header does not contain JSESSIONID header, it will automatically create one for you and return it.

    The bottom layer of session technology is actually implemented based on Cookie technology. If there is no Cookie, send the request when request. Getsession(); Once the session object is created, the server (Tomcat) will create a Cookie object whose key value is JSESSIONID. Then, each time a request is made, the sessionid will be sent to the server in the form of a Cookie. request.getSession(); The previously created session object will be found according to the id value of the Cookie.

  1.3.5. Session application

1) Login verification

HttpSession session=request.getSession();
User u=(User) session.getAttribute("user");
if(u==null){
   request.setAttribute("error", "Please enter your user name and password to log in");
   //If you have not logged in before, forward to the login page
   request.getRequestDispatcher("login.jsp").forward(request, response);
   return;
}

2) Verification code application

Step 1: create a login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>

<!DOCTYPE html>
<html>
<head>
<title>login</title>
</head>
<body onload="changeCode('ImageServlet');">
	<form action="/LoginServlet" method="post">
		user name: <input type="text" name="username"><br> 
		password: <input type="password" name="password"><br> 
		Verification Code: <input type="text" name="checkcode"> 
		<a href="javascript:changeCode('ImageServlet')"><img id="codeimg"  style="width: 60px;height:20px;"><br></a>
		<br> <input type="submit" value="Sign in">
	</form>
</body>
<script type="text/javascript">
function changeCode(url){
	window.document.getElementById("codeimg").src=url+"?"+Math.random();
}

</script>
</html>

Step 2: create a new LoginServlet

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet{

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("login.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=GBK");
	      PrintWriter out = response.getWriter();
	      //Get the user's username and userpsw and authentication code
	      String username=request.getParameter("username");
	      String userpsw=request.getParameter("userpsw");
	      String checkCode=request.getParameter("checkcode");
	      String checkCode2=(String) request.getSession().getAttribute("checkcode");
	      System.out.println(checkCode+"=="+checkCode2);
	      if(checkCode!=null && checkCode.toUpperCase().equals(checkCode2)){
	    	  response.getWriter().write("Login successful!");
	      }
	      else{
	         request.getRequestDispatcher("login.jsp").forward(request, response);
	         if(checkCode==null) {
	        	 System.out.println("Verification code is empty!"); 
	        	 return;
	         }
	         request.setAttribute("err", "Incorrect verification code");
	         System.out.println("Incorrect verification code!");
	      }
	      out.flush();
	      out.close();
	}
}

Step 3: create a new ImageServlet

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		  // 7. Prohibit the browser from caching random pictures
	      response.setDateHeader("Expires", -1);
	      response.setHeader("Cache-Control", "no-cache");
	      response.setHeader("Pragma", "no-cache");
	      // 6. Notify the client to open and send past data in the form of pictures
	      response.setHeader("Content-Type", "image/jpeg");
	      // 1. Create a picture in memory
	      BufferedImage image = new BufferedImage(60, 30,
	      BufferedImage.TYPE_INT_RGB);
	      // 2. Write data to the picture
	      Graphics g = image.getGraphics();
	      // Set background color
	      g.setColor(Color.BLACK);
	      g.fillRect(0, 0, 50, 20);
	      // 3. Set the color and font of the written data
	      g.setColor(Color.RED);
	      g.setFont(new Font(null, Font.BOLD, 20));
	      // 4. Write data to the picture
	      String num = makeNum();
	      // This sentence is to save the randomly generated value to the session
	      request.getSession().setAttribute("checkcode", num);
	      System.out.println("Current verification code:"+num);
	      // Through the session, you can directly go to the generated verification code
	      g.drawString(num, 0, 20);
	      // 5. Output the written data picture to the browser
	      ImageIO.write(image, "jpg", response.getOutputStream());
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
	
	// This function generates 7 digits at random
   public String makeNum(){
      String str = "0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ";
      String s = "";
      for (int i = 0; i < 4; i++){
         int k = (int) (Math.random() * 36);
         s = s + str.charAt(k);
      }
      return s;
   }
}

Case effect:

1.3.6 summarize the differences between cookie s and session s

1) Storage location

    The Cookie exists in the temporary folder of the client;

    Session is stored in the server memory, and a session domain object serves a user browser.

2) Security

    Cookie s are stored in clear text on the client, with weak security, and can be encrypted and stored in md5;

    Session is stored in the server memory, so it is safe. Because the session will occupy the server memory, do not store too many large objects into the session, which will affect the performance.

3) Network traffic

    Cookie s will pass information to the server;

    The attribute value of Session will not be given to the client.

4) Life cycle

    The life cycle of a cookie is the cumulative time. For example, set setMaxAge(30, 30S) for the cookie and it will expire;

    The life cycle of a session is the interval time. For example, set the session for 20min. If the session is not accessed within 20min, the session will become invalid.

Topics: Java Tomcat