The principle of cookie and session and its application in Servlet


insert image description here

Introduction

The cookie is saved on the client side, and the session is saved on the server side. Both are used to describe the state of a session. The server can create multiple cookie objects to respond to the client and save them on the client; when the browser client sends a request, it automatically carries all the cookie information under the corresponding request path for the server to respond to. The server can also obtain a unique session object corresponding to each client, and obtain some attributes in the object to verify the illegal operation of the user. Here is just a general introduction to the status of the two.


cookie

The essence and implementation principle of cookies

  • Cookie is actually a relatively persistent storage mechanism of the browser, which optimizes the defects caused by the stateless nature of the Http communication protocol and greatly improves the user experience

For example, a certain sdn and a certain video can choose to save the user's login information when the user logs in for the first time, and the user can directly realize the effect of automatic login when entering the webpage within a certain period of time. Greatly optimized the user experience. This is because the cookie information corresponding to our account is stored on the local hard disk. When we manipulate the client to send a request to the corresponding server, the saved cookie information will be automatically sent. The server receives and verifies this information so that we can Realize the effect of objectively "login-free".

  • Cookies provide an effective way for our browsers to access hard disk files

For the safety of the computer, the browser prohibits the js code from accessing the data on the local disk. The cookie mechanism provides a means for the browser to access hard disk files, so there is a persistent storage.

  • Multiple cookies can be created by the server, and then responded to the client and stored in the client's running memory or hard disk space according to the requirements. When the user sends a request to the server, the client will automatically send the request information with the cookie. The server side recognizes and parses the cookie information for response operation.

For example, when the client successfully logs in for the first time, the server creates two cookie information containing the user name and user password respectively, and stores the response in the memory or hard disk space of the client. If it is stored in the memory, then the effect that the client can automatically log in to the website multiple times during a session can be realized; The same session can achieve the effect of automatic login. Greatly optimized user experience. If a regular website prompts the user to log in every time it is opened, what a maddened customer it is! The functional schematic diagram of the cookie is as follows, taking the user’s login-free as an example:
Cookies within a certain implementation to achieve free login renderings

  • The cookie mechanism is not a unique mechanism in Java, but a part of the http protocol, but there is a cookie class corresponding to it in Jaba; each cookie is composed of name=value, and the types of both are string

As long as it is doing web development, no matter what programming language it is, the cookie mechanism is essential. Whether it is a client or a server, the cookie format sent is in the form of a key-value pair, and the name or value obtained by the server is in the form of a string


Application of cookie in Servlet

  • Create a cookie object on the server side
Cookie cookie = new Cookie(String name,String value);  //Cookie类只提供了这一种形式的构造方法
  • The server side sets the life cycle and associated path of the cookie object.
cookie.setMaxAge(int second);	//设置cookie的生命周期的参数是以秒为单位的。
								//例如,设置一个cookie的生命周期为10天,可以设置参数为60*60*24*10
cookie.setPath(String url);		/*当服务器端将cookie对象相应保存到客户端时,当客户端发送在这里设置的请求
								在这里设置的请求路径时,会自动将与该路径相关的所有cookie信息包含在请求体中发送给服务器

About the life cycle of the cookie object set on the server side

  • cookie.setMaxAge(second > 0): The cookie object survives for second seconds, and the client stores the cookie object on the local disk after receiving it
  • cookie.setMaxAge(second = 0): delete this cookie object
  • cookie.setMaxAge(second < 0): Store this cookie object in the browser memory, which takes effect in one session, and the cookie will become invalid when the browser window is closed
  • The server responds to the cookie object after setting the life cycle and path to the client, and stores the cookie object in the client's memory or hard disk space
response.addCookie(Cookie var);
  • The server side receives the cookie information sent by the client
Cookie cookies[] = request.getCookies();	//返回客户端发送的该路径下的所有cookie信息

About the server obtaining the cookie information sent by the client
      The server obtains all the corresponding cookie information under the request path sent by the client through the getCookies() of the request object, and returns an array of cookies. If no cookie information from the client is obtained, null will be returned, and a cookie array with a length of 0 will not be created and returned


session

The essence and realization principle of session

  • The session object is stored on the server side, which is essentially a mechanism for the server side to share data.

A session corresponds to a session object. Multiple sessions correspond to multiple session objects. You can add attributes to this session object on the server side, and all requests in this session will share this session object

  • In the web container, the session is actually stored in a form similar to a map collection. Multiple clients send requests corresponding to different session objects. Similar to the key value of the map collection, the sessionid of the session object is stored. This sessionid will It responds to the client in the form of a cookie for storage; the value similar to the map collection stores the specific session object corresponding to the key value. The implementation principle of seesion in the web container is as follows:insert image description here
  • When the user sends a request for the first time, the server will create a new session object, and can add attributes to the session object, and at the same time associate a unique sessionid with the session object and return it to the client in the form of a cookie for storage ; When the user sends a request not for the first time, the request body including the sessionid will be automatically sent to the server, and the server can find the corresponding session object according to the sessionid in the cookie information to respond. As shown in the figure below:
    insert image description here
    I don’t know if you have noticed that when you leave a webpage without any operation for a long time and perform operations on the webpage again, the webpage may prompt you to log in again. This self-protection mechanism of the webapp is through The session object is implemented. The session object can have a valid duration. When the session object is not accessed within the valid period, it will be automatically destroyed. Therefore, when the user requests again, the server cannot find the session object corresponding to the sessionid sent by the requesting user. This is why the server will think that you are accessing this session illegally. For webapp, for its own security, the server will let the user log in again to check whether the user's identity is legal.
    For a webapp, a session refers to when the user opens the browser and sends the first request until the user closes the browser. When the user closes the browser, the session becomes invalid. However, the web server disconnects from the client after the end of the response, and does not know that the user has closed the browser, so the session object corresponding to the user's current session may still exist. This is why the client of the online banking app will display a safe exit button. By clicking this button, the user can tell the server that I am leaving, and let the server manually destroy the session object corresponding to this session in the web container to ensure the safety of the user and the server. .

Application of session in Servlet

  • Create/get session object on the server side
HttpSession session = request.getSession();

About server-side creation/acquisition of session objects
   The server-side creates/acquires session objects through the getSession object of the HttpServletRequest object. When the user sends a request in the session for the first time, there is no session object on the server side for the session corresponding to the user, and the getSession() method will create a session object for the user. When the user sends a request not for the first time, the getSession method will return the session object corresponding to the user.insert image description here

  • The server side manipulates the properties of the session object
session.setAttribute(String name,Object o);	//向该会话的session对象中添加属性
Object o = session.getAttribute(String var);//获取该会话中session中的属性
session.removeAttribute(String var);	    //移除该会话对应session对象中的var属性及其value
  • The server side destroys the session object
session.invalidate();

HttpServletRequest,Session,ServletContext

All three can be used as a tool for data domain sharing, so what is the difference?

  • The first is HttpServletRequest, also known as the request domain, for data sharing at the request level

The life cycle of the request object is very short. When a request ends, the request object will be destroyed, and the data in the request field will no longer exist. This data field sharing method is often used between different request forwarding

  • The second is Session, also known as session domain, which is user-level

A session of a user corresponds to a session object, and the data added in this session object can be shared no matter which request is made in this session. Different user sessions correspond to different sessions, and each session object is associated with an individual customer

  • Finally, ServletContext, also known as application domain, is project-level

The shared data field added to the ServletContext object is the entire project, and the size relationship between the three fields shared by all clients

  • HttpServletRequest < Session < ServletContext

The principle of using the three

  • Use as small a domain as possible

Guess you like

Origin blog.csdn.net/weixin_64450588/article/details/129805784