Java web-5 session and its session Technology

Keywords: ASP.NET Operation & Maintenance server

1, Cookie (saved on client)

1. What is a Cookie

Cookie(s) is actually a small text file. The information content exists in the form of key value. A cookie is like a membership card of a mall. When a user visits the website through the browser, the website server can save some necessary information in the cookie and return it to the browser through the response object. The browser will save it locally. When the next time the website is changed, These cookies will be sent to the web server together, and the web server can respond according to the information in the cookie

  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 data
                * Cookie[]  request.getCookies() 

  2.cookie mechanism

When a user visits and logs in a website for the first time, the setting and sending of cookie s will go through the following four steps:

The client sends a request to the server -- "the server sends an HttpResponse response to the client, which contains the header of the set cookie --" when the client saves the cookie and then sends a request to the server, the HttpRequest request will contain the header of a cookie -- "the server returns the response data

  3.cookie attribute item

2, [case] displays the last access time of the user  

  1. Save the user's last access time through a cookie

package cn.itcast.chapter05.cookie.example;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
public class LastAccessServlet extends HttpServlet {
   private static final long serialVersionUID = 1L;
   public void doGet(HttpServletRequest request, 
	                        HttpServletResponse response)
				throws ServletException, IOException {
			// Specify the encoding method UTF-8 of the server output content to prevent garbled code
			String lastAccessTime = null;
	         // Get all cookie s and store them in the array
			Cookie[] cookies = request.getCookies();
			// Traversal cookie array
			for (int i = 0; cookies != null && i < cookies.length; i++) {
				if ("lastAccess".equals(cookies[i].getName())) {
					// If the name of the cookie is lastAccess, get the value of the cookie
					lastAccessTime = cookies[i].getValue();
			// Determine whether there is a cookie named lastAccess
			if (lastAccessTime == null) {
				response.getWriter().print("This is your first visit to this site!!!");
			} else {
			     response.getWriter().print("Your last visit was: " 
	                           + lastAccessTime);//Display the last time until browsing is finished
			// Create a cookie and send the current time to the client as the value of the cookie
			String time=String.format("%tF%<tF", new Date());
			Cookie cookie = new Cookie("lastAccess",time);
			Cookie cookie1 = new Cookie("dashujv","2004");
	    public void doPost(HttpServletRequest req, HttpServletResponse resp)
				throws ServletException, IOException {
			this.doPost(req, resp);

Configure the mapping information and view the running effect

Note: LastAccessServlet sends a Cookie to the browser to save the user's access time

Visit again


Third visit


Note: the access time is not displayed, indicating that the cookie information stored in the browser has been deleted. This is because by default, the value of the max age attribute of the cookie object is - 1 (that is, the browser closes and the cookie object is deleted)

Set it through the setMaxAge() method to make the cookie object have a long survival time on the client. For example, set the effective time to 1 hour



  1. Can I send multiple cookie s at a time?
            * Yes, you can create multiple cookie objects and send cookies by calling the addCookie method multiple times with response.
        2. How long is the cookie saved in the browser?
            1. By default, when the browser is closed, the Cookie data is destroyed
            2. Persistent storage:
                * setMaxAge(int seconds)
                    1. Positive number: persistent storage. Write Cookie data to a file on the hard disk. Depending on the time setting
                    2. Negative number: default value
                    3. Zero: delete cookie information
        3. cookie Chinese problem
            * Before tomcat 8, Chinese data cannot be stored directly in cookie s.
                * Chinese data needs to be transcoded --- generally URL code (% E3)
            * After tomcat 8, cookie s support Chinese data. Special characters are not supported. It is recommended to use URL encoding for storage, decoding and parsing
        4. cookie sharing in web projects
            1. cookie sharing of multiple web projects among the same tomcat server
                * Cookies cannot be shared by default
                * 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 "/"
            2. cookie sharing of multiple web projects among 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
                    * setDomain(""), then cookie s in and 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
            3. The total number of cookie s under the same domain name is also limited (20)
        * effect:
            1. Cookies are generally used to store less and less important data (because they are unsafe)
            2. Complete the identification of the client by the server without logging in

  3, Session (saved on the server)

1. What is a Session

  Get HttpSession object:            

 HttpSession session = request.getSession();

Session is called "session control". Session refers to the same session from the time the user opens the browser to visit a website, no matter how many pages and links he visits in the website. It belongs to the same session until the user closes the browser. Session is also used to save information, but different from the visible and storage restrictions of cookie s to users, session is saved on the server and not visible to users, but it can also realize the function of sharing information in the same site (usually sharing user login information...)

  2.Session mechanism

The user accesses the server - > the server determines whether it is the first connection - > the first connection creates a new session containing a unique ID value - > the ID value will be returned to the user in the form of cookie information (key = jssessionid, value = ID) for saving, and the user's identity will be identified by the following times - > when the user accesses again, the server can judge that the user has accessed

3.Session attribute item  


Generally speaking, the Session timeout will be configured during project use. If it is not configured, the default value is 30 minutes, that is, after the user does not operate for 30 minutes, the Session will become invalid. At this time, the user needs to log in to the system again.

The Session timeout is mainly configured in the web.xml of the project, as follows:

     <session-timeout>30</session-timeout>  //Set to 0 or a negative number and the session will never time out

  Note: the session is forcibly invalidated by the invalidate () method


  1. After the client is shut down, the server does not shut down. 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());

        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; If the same, you must ensure that the data is not lost. tomcat does the following automatically
                * Passivation of session: serialization process
                    * Serialize the session object to the hard disk before the server shuts down normally
                * Activation of session: deserialization process
                    * 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    
      5. 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

4, [case] implement shopping cart

How to rewrite a URL

  1. For ListBookServlet   In class   for   The code in the loop is modified to change the requested access path to URL rewriting

for(Book b:books) {
			String name=b.getName();
			String id=b.getId();
			String url="<a href='purchares?id="+id+"'>Purchase record</a>";
			out.print("Book Name:"+name+" "+url+"<br/><br/>");
			System.out.println("Book Name:"+name+" "+url+"<br/><br/>");

Note: when rewriting the URL, get the session object through getsession()

2. Modify the purchaseservlet

String id=request.getParameter("id");
		System.out.println("id : "+id);
		if(id==null) {

3. Restart

  Note: no matter whether the browser supports cookies or not, when the user accesses the program for the first time, because the server does not know whether the user's browser supports cookies, the URL address will be rewritten in the first response page. If the user's browser supports cookies, the Session identification number will be passed to the server using the request header field of cookies in subsequent visits. Therefore, the server determines that the browser supports cookies and will not rewrite the URL in the future. If the header information of the browser does not contain the Cookie request header field, the URL needs to be rewritten in each subsequent response. In addition, in order to avoid that some functions of other websites cannot be used normally, it is usually necessary to enable the Cookie function.

5, [case] realize user login

Website header interface

package cn.itcast.chapter05.session.example02;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class IndexServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws ServletException, IOException {
          // Solve the problem of garbled code
         // Create or obtain a Session object that stores user information
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			"You haven't logged in yet, please<a href='/chapter05/login.html'>Sign in</a>");
		} else {
            response.getWriter().print("You have logged in, welcome," + user.getUsername() + "!");
					"<a href='/chapter05/LogoutServlet'>sign out</a>");
			// Create a Cookie to store the identification number of the Session
			Cookie cookie = new Cookie("JSESSIONID", session.getId());
			cookie.setMaxAge(60 * 30);
	public void doPost(HttpServletRequest request, 
                           HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);

Login success interface

public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		String username = request.getParameter("username");
	String password = request.getParameter("password");
	PrintWriter pw = response.getWriter();
        //Suppose the correct user name is Lily and the password is 123
		if (("LiLy").equals(username) && ("123").equals(password)) {
		User user = new User();
	request.getSession().setAttribute("user", user);
	} else {
		pw.write("User name or password error, login failed");

User logout

public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
     // Remove the User object from the Session object
	public void doPost(HttpServletRequest request, 
       HttpServletResponse response)throws ServletException, IOException {
		doGet(request, response);

  Verification code setting

public void doGet(HttpServletRequest request,HttpServletResponseresponse)throwsServletException, IOException {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String checkCode = request.getParameter("check_code");
			String savedCode = (String) request.getSession().getAttribute(
			PrintWriter pw = response.getWriter();
			if (("Lily").equals(username) && ("123").equals(password)
					&& checkCode.equals(savedCode)) {
				User user = new User();
				request.getSession().setAttribute("user", user);
			} else if (checkCode.equals(savedCode)) {
				pw.write("User name or password error, login failed");
			} else {
				pw.write("Verification code error");

Verification code picture

 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.awt.*;
 import java.awt.image.*;
 import javax.imageio.ImageIO;
 public class CheckServlet extends HttpServlet
 	private static int WIDTH = 60; //Verification code picture width
 	private static int HEIGHT = 20; //Verification code picture height
 public void doGet(HttpServletRequest request,HttpServletResponse response) 
 			throws ServletException,IOException{		
 		HttpSession session = request.getSession();
 		ServletOutputStream sos = response.getOutputStream();
 		//Set the browser not to cache this picture
 		response.setDateHeader("Expires", 0);
 		//Create a memory image and get its graphics context
 		BufferedImage image = 
 			new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); 
 		Graphics g = image.getGraphics();
 		//Generate random authentication code
 		char [] rands = generateCheckCode();
 		//Generate image
 		//End the drawing process of the image and complete the image
 		//Output image to client
 		ByteArrayOutputStream bos = new ByteArrayOutputStream();
 		ImageIO.write(image, "JPEG", bos);
 		byte [] buf = bos.toByteArray();
 		//The following statement can also be written as: bos.writeTo(sos);
 		//Save the current verification code into the Session
 		session.setAttribute("check_code",new String(rands));
 		//There will be a problem using the following code directly. The Session object must be obtained before submitting the response
 	//request.getSession().setAttribute("check_code",new String(rands));
        //Generate a 4-character verification code
 	private char [] generateCheckCode()
 		//Character table defining verification code
 		String chars = "0123456789abcdefghijklmnopqrstuvwxyz";
 		char [] rands = new char[4];
 		for(int i=0; i<4; i++)
 			int rand = (int)(Math.random() * 36);
 			rands[i] = chars.charAt(rand);
 		return rands;
 	private void drawRands(Graphics g , char [] rands)
 		g.setFont(new Font(null,Font.ITALIC|Font.BOLD,18));
 		//Output each character of the verification code at different heights		
 		g.drawString("" + rands[0],1,17);
 		g.drawString("" + rands[1],16,15);
 		g.drawString("" + rands[2],31,18);
 		g.drawString("" + rands[3],46,16);
 	private void drawBackground(Graphics g)
  		//Painting background
 		g.setColor(new Color(0xDCDCDC));
 		g.fillRect(0, 0, WIDTH, HEIGHT);
 		//Randomly generate 120 interference points
 		for(int i=0; i<120; i++)
 			int x = (int)(Math.random() * WIDTH);
 			int y = (int)(Math.random() * HEIGHT);
 			int red = (int)(Math.random() * 255);
 			int green = (int)(Math.random() * 255);
 			int blue = (int)(Math.random() * 255);
 			g.setColor(new Color(red,green,blue));		






Cookie s are different from sessions in the following ways:

1) Cookie and HttpSession are technologies for saving Session related data. Cookie stores information in the browser, which is a client technology, and Session saves data in the server, which is a server technology

2) Cookies work based on the set Cookie response header and Cookie request header in the HTTP protocol

3) By default, HttpSession works based on a special Cookie named JSESSIONID

4) The browser has strict restrictions on cookies. There is a limit on how many cookies a website can save in the browser

5) HttpSession operates based on cookies by default.





Posted by sunnypal on Fri, 05 Nov 2021 11:00:26 -0700