Servlet learning series (4)

1. Conversation technology

(1) What is conversation technology

The user opens the browser, clicks on multiple hyperlinks, accesses multiple web resources on the server, and then closes the browser. This process is called a session.

(1) What problem does the conversation technology solve?

Save each client's own data, each user will inevitably generate some data in the process of using the browser to talk to the server. The program must save these data for each user.

2. Introduction to Cookie and Session

(1) Problems with the storage of data in the Request domain and ServletContext

1. Request domain

The problem of using request domain storage is that the life cycle of the request domain is created at the beginning of the request and destroyed after the request ends. There is no way to store multiple data.

2、ServletContext域

The problem with using servletcontext is that servletcontext has a long life cycle. It is created when the server is started, and destroyed when the server is shut down. Data stored here can easily cause data confusion among various browsers and waste browser resources.

(二)、Cookie

Cokie is a session technology and a domain. It can also store data in storage.

Cookie technology means that the server stores data in the browser cache, and when the server is used, it will be called by the client's browser.

(Three), Session

Session is also a domain, which is different from Cookie. It is stored on the server. It is created when the browser accesses the server. It will create a Seeion domain for the browser to store the browser’s data. It will be stored when the service is closed or expired. destroy.

3. Use of Cookies

(1) Store Cookies in the browser cache

  1. Create cookie
    • Cookie cookie = new Cookie(String cookieName,StringcookieValue);
    • Cookies will be sent to the client in the form of corresponding headers
    • Cookies can only store non-Chinese character strings
  2. Respond to the browser
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
       
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
    
    
//		1、创建Cookie
		Cookie cookie = new Cookie("name1","Cookie");
//		2、响应给浏览器
		response.addCookie(cookie);
	}

}

Visit result

  • First visit (get the current time, write it into the cookie, and respond to the browser)

  • Second visit (cookie information can be seen in the request header)

  • Access to any resources of the server, under normal circumstances will bring cookies

(2) Set the time of cookie persistent storage

By default, cookies are at the session level, that is, opening the browser and closing the browser is regarded as a session. If you do not set its persistent storage time, the cookie will be stored in the browser's memory, and the cookie information will be destroyed when the browser is closed.
Set storage time

@WebServlet("/CookieServlet")
public class CookieServlet2 extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
       
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
    
    
//		1、创建Cookie
		Cookie cookie = new Cookie("name1","Cookie");
//		设置持久化存储时间
		cookie.setMaxAge(60);
		
//		2、响应给浏览器
		response.addCookie(cookie);
	}
}

note:

The unit of the setting time is seconds. If the persistent storage time is set, the cookie information will be stored in the browser disk file and will be automatically deleted after expiration.

(Three), set the cookie carrying path

When accessing a certain resource, whether to carry cookie information every time, if external resources carry it every time, it will affect the transmission speed.
If the carrying path is not set, the cookie information will be carried in the same path that accesses the web resource that created the cookie by default.

@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
//		1、创建Cookie
		Cookie cookie = new Cookie("name1","Cookie");
//		设置持久化存储时间
		cookie.setMaxAge(60);
//		设置携带路径    默认路径:http://localhost:8080/Cookie/CookieServlet
		cookie.setPath("/Cookie/CookieServlet");
//		2、响应给浏览器
		response.addCookie(cookie);
	}

}

(4) Delete Cookie's delicate information

To delete the cookie information is to set the parameter of the setMaxAge(0) method to 0.

protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
    
    
//		1、创建Cookie
		Cookie cookie = new Cookie("name1","Cookie");
//		删除Cookie信息
		cookie.setMaxAge(0);

(5) Get the specified cookie

Get all the cookie information through the getCookies() method of the Request object, and you need to traverse to find out what you need

@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
    
    
	private static final long serialVersionUID = 1L;
       
	protected void service(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
    
    
//		获取所有的coookie
		Cookie[] cookies = request.getCookies();
		if(cookie != null) {
    
    
			for (Cookie C : cookies) {
    
    
				String name = C.getName();
				if(name.equals("name")) {
    
    
					response.getWriter().write("name = value"+C.getValue());
				}
			}
		}
	}
}

Four, Session use

Session technology is a technology that stores data on the server side. It creates a memory space for each client to store the client's data. The client needs to carry an identification ID every time to find its own memory space in the server. Session needs to use Store the unique identification SESSIONID of the customer in the Cookie.

(1) The life cycle of the Session domain

  1. create
    • Created when request.getSession() is executed for the first time.
  2. destroy
    • When the server is down
    • Session expiration/invalidation (default 30 minutes), it is timed from the end of the last operation
    • Manually destroy, call the invalidate() method
  3. Scope of action
    • The default is in a session, which means that any resource in a session shares a session object

(2), Session domain persistent JSessionID

Because the session is at the session level, when an object is placed in the session, it only exists in the session in the current dialog window. When the current window is closed, the session is gone. When we want to persist this session, we need to use the JSESSIONID in cooik. Let's first understand the operating mechanism of session.

  1. The Session object is created on the server side when a request is sent to the server for the first time, and the object has a unique ID

  2. When the Session object is created, a special Cookie object is created. The name of the Cookie object is a fixed value JSESSIONID. The value of the object is the ID value of the Session object. At the same time, this special Cookie object is sent to the browser.

  3. In the future, the browser will carry this special Cookie object when sending

  4. After the server obtains the value of the Cookie object of JESSIONID, it searches the server for the corresponding Session object to distinguish
    the acquisition of different user session objects: HttpSession session = request.getSession()

So we want to persist the Session object, we only need to persist the Cookie object corresponding to JSESSIONID.
//获取Cookie对象
         Cookie[] cookies = request.getCookies();
         if(cookies != null){
    
    
             for (Cookie cookie : cookies) {
    
    
                 //获取Cookie的名字
                 String name = cookie.getName();
                 if("JSESSIONID".equals(name)){
    
    
                      //持久化该Cookie对象
                      cookie.setMaxAge(60);
                      //将Cookie对象发送给浏览器
                      response.addCookie(cookie);
                 }
             }
         }

In this case, the session will be persisted. In fact, the session is a special kind of Cookie.

Guess you like

Origin blog.csdn.net/weixin_44676935/article/details/105515011