Conversation and its technology

Keywords: ASP.NET Operation & Maintenance server

Cookie (saved on client)

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()
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, including the header of the set cookie -- the client saves the cookie, and then sends a request to the server, the HttpRequest request will include the header of a cookie -- the server returns the response data
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.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/LastAccessServlet")
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
            response.setContentType("text/html;charset=utf-8");
            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");
            response.addCookie(cookie);
            response.addCookie(cookie1);
            
        }
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            this.doPost(req, resp);
        }
    }


View the results of the operation:

Visit again:

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

  Summary:

1.Cookie can create multiple cookie objects, and use response to call addCookie method multiple times to send cookies;

2. Save time of cookie in browser:

   By default, when the browser is closed, the Cookie data is destroyed
                    Persistent storage: * setMaxAge(int seconds)
                    Positive: persistent storage. Write Cookie data to a file on the hard disk. Depending on the time setting
                    Negative: default
                    Zero: delete cookie information

three   Characteristics and functions of cookies
        * characteristic:
                Cookie s store data in the client browser
                The browser has a limit on the size of a single Cookie (4kb) and
                The total number of cookies under the same domain name is also limited (20)
        * effect:
                Cookie s are generally used to store less and less important data (because they are unsafe)
        .       Complete the identification of the client by the server without logging in

4.cookie Chinese question:
             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

5.cookie sharing in web project
                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 "/"
                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(".baidu.com"), then cookie s in tieba.baidu.com and news.baidu.com can be shared   

The Session is saved on the server

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;

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) and saved. The user identity can be identified by the following times - > the user accesses again, and the server can judge that the user has accessed;

Summary:

1. After the client is shut down, the server does not shut down, and the two session s are not the same by default;

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);

2. The client is not closed. After the server is closed, the two session s obtained are 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     
                <session-config>
                    <session-timeout>30</session-timeout>
                </session-config>
  5. session features:
           Session is used to store the data of multiple requests of a session and exists on the server side;
           session can store data of any type and size;

Realize the shopping cart with questions:

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/>");
        }

Modifying the purchaseservlet

String id=request.getParameter("id");

System.out.println("id : "+id);

if(id==null) {

response.sendRedirect("list");

return;

}

Restart:

Implement user login

Website header interface code:

package cn.itcast.chapter05.session.example02;
import java.io.IOException;
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
		response.setContentType("text/html;charset=utf-8");
         // Create or obtain a Session object that stores user information
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		if (user == null) {
			response.getWriter().print(
			"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() + "!");
			response.getWriter().print(
					"<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);
			cookie.setPath("/chapter05");
			response.addCookie(cookie);
		}
	}
	public void doPost(HttpServletRequest request, 
                           HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}

Login successful interface code:

public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	response.setContentType("text/html;charset=utf-8");
		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();
			user.setUsername(username);
		user.setPassword(password);
	request.getSession().setAttribute("user", user);
			response.sendRedirect("/chapter05/IndexServlet");
	} else {
		pw.write("User name or password error, login failed");
		}

     }

  User logoff Code:

public class LogoutServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
     // Remove the User object from the Session object
		request.getSession().removeAttribute("user");
		response.sendRedirect("/chapter05/IndexServlet");
	}
	public void doPost(HttpServletRequest request, 
       HttpServletResponse response)throws ServletException, IOException {
		doGet(request, response);
	}
}

   Verification code setting:

public void doGet(HttpServletRequest request,HttpServletResponseresponse)throwsServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String checkCode = request.getParameter("check_code");
            String savedCode = (String) request.getSession().getAttribute(
                    "check_code");
            PrintWriter pw = response.getWriter();
            if (("Lily").equals(username) && ("123").equals(password)
                    && checkCode.equals(savedCode)) {
                User user = new User();
                user.setUsername(username);
                user.setPassword(password);
                request.getSession().setAttribute("user", user);
                response.sendRedirect("/chapter05/IndexServlet");
            } else if (checkCode.equals(savedCode)) {
                pw.write("User name or password error, login failed");
            } else {
                pw.write("Verification code error");
            }
        } 

 
  Verification code picture:

import java.io.*;
 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();
 		response.setContentType("image/jpeg");
 		ServletOutputStream sos = response.getOutputStream();
 		//Set the browser not to cache this picture
 		response.setHeader("Pragma","No-cache");
 		response.setHeader("Cache-Control","no-cache");
 		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
 		drawBackground(g);
 		drawRands(g,rands);
 		//End the drawing process of the image and complete the image
 		g.dispose();
 		//Output image to client
 		ByteArrayOutputStream bos = new ByteArrayOutputStream();
 		ImageIO.write(image, "JPEG", bos);
 		byte [] buf = bos.toByteArray();
 		response.setContentLength(buf.length);
 		//The following statement can also be written as: bos.writeTo(sos);
 		sos.write(buf);
 		bos.close();
 		sos.close();
 		//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.setColor(Color.BLACK);
 		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);
 		System.out.println(rands);
 	}
 	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));		
 			g.drawOval(x,y,1,0);
 		}
 	}
}

Cookie s are different from sessions in the following ways:
Cookie and HttpSession are technologies for saving Session related data, in which cookie stores information on the browser side, which is a client technology, and Session saves data on the server side, which is a server-side technology;

Cookies work based on set Cookie response header and Cookie request header in HTTP protocol;

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

The browser has strict restrictions on cookies. There are restrictions on how many cookies a website can save in the browser;

HttpSession operates based on cookies by default;

Posted by mikesab on Sun, 07 Nov 2021 17:24:26 -0800