Cookie httpsession data sharing implementation

Implementation of data sharing among multiple servlets

  • Data sharing: After the work of oneservlet is finished, the data generated is handed over to twoservlet for use.
  • Four data sharing schemes are provided in the servlet specification.
    • servletcontext interface
    • cookie class
    • httpSession interface
    • httpservletrequest interface

servletContext interface

Introduction:

  • An interface from the servlet specification, which exists in servlet-api.jar in tomcat

Responsible for providing the interface implementation class of this interface in tomcat.

  • If two servlets come from the same website, they can share data with each other through the website’s servletContext instance object
  • Developers are used to calling the servletContext object [global scope object]

principle

Every website has a global scope object, this global scope object [equivalent to a MAP].

In this website, oneservlet can store a piece of data into the global scope object,

Other servlets in the current website can get this data from the global scope object for use at this time.

Global scope object life cycle

  1. During the startup of the http server, a global scope object is automatically created in memory for the current website
  2. During the operation of the http server, there is only one global scope object in a website
  3. During the operation of the htpp server, the global scope object is always alive
  4. When the http server is about to shut down, it is responsible for destroying the global scope objects in the current website.

The life cycle of global scope objects runs through the entire runtime of the website

Command implementation

[Same website] Oneservlet shares data with twoservlet

oneservlet{
    
    
	public void doget(httpservletrequest request,httpservletresponse response){
    
    
	//1.通过【请求对象】向tomcat索要当前网站中的【全局作用域对象】
	ServletContext application = request.getservletcontext();
	//2.将数据添加到全局作用域对象作为【共享数据】
	application.setAttribute("key1",数据)//map类型
	}
}



twoservlet{
    
    
    public void doget(httpservletrequest request,httpservletresponse response){
    
    
        //1.通过【请求对象】向tomcat索要当前网站中的【全局作用域对象】
        ServletContext application = request.getservletcontext();
        //2.从全局作用域对象中得到指定关键字所对应的数据
        Object 数据 = application.getAttribute("key1");
    }
}

cookie

Introduction

  • The cookie comes from a tool class in the servlet specification and exists in the servlet-apijar package provided by tomcat

  • If two servlets come from the same website and provide services for the same browser/user , then use the cookie object for data sharing

  • Cookie stores the private data of the current user, and improves the quality of service in the process of sharing data

  • In real life scenarios, cookies are equivalent to users getting [membership card] on the server

cf70f713540c1f48aaf3baa6aa7af69

principle

The user sends a request to the myweb website to apply for oneservlet for the first time through the browser.

Oneservlet creates a cookie during runtime to store data related to the current user.

After oneservlet finishes working, 【write cookie into response header】return to the current browser.

After the browser receives the response packet, it stores the cookie in the browser cache.

After a period of time, when the user initiates a request to [myweb site] to apply for two servlet again through the same browser , the browser needs to unconditionally send the [cookie written to the request header ] that was previously pushed by the myweb site .

At this time, when twoservlet is running, it can obtain the shared data provided by oneservlet by reading the cookie information in the request header.

Implementation command

The same website oneservlet and twoservlet realize data sharing with the help of cookies

The browser initiates a request to myweb for the first time to access oneservlet

oneservlet{
    
    
	public void doget(request,response){
    
    
		//1.创建一个cookie对象来保存共享数据(当前用户数据)
		//cookie相当于一个map
		// 一个cookie中只能存放一个键值对
		//这个键值对中的key和value只能是String
		//键值对中的key不能是中文
		cookie card1 = new cookie("key1","abc");
		cookie card2 = new cookie("key2","efg");
		//2.将cookie写入到响应头中交给浏览器
		response.addCookie(card1);
		response.addCookie(card2);
	}
}

Browser/User Response Package [200]

​ 【cookie:key1 = abc; cookie:key2 = efg】

​ 【】

​ [Processing results]

The browser sends a second request to the myweb website to access twoservlet------>request package

Request package [url method]

​ [Request parameters: xxx

​ cookie key1 = abc; cookie key2 = efg;】

​ 【】

​ 【】

twoservlet{
    
    
	public doget(request,response){
    
    
		//1.调用请求对象从请求头得到浏览器带来的cookie
		Cookie cookieArray[] = request.getCookies();
		//2.循环遍历数组,得到每一个cookie的key和value
		for(Cookie card:cookieArray){
    
    
			String key = card.getname();//读取key
			String value = card.getvalue();//读取value
		}
	}
}

Cookie simulation card consumption function

[External link image transfer failed. The source site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-bC3g9ARj-1614267968963)(C:\Users\ThinkPad\AppData\Local\Temp\WeChat Files\73c79877758b343d5e4cc44d8068064.jpg )]

Timing of cookie destruction

  • By default, the cookie object is stored in the browser cache. As long as the browser is closed, the cookie object is destroyed.
  • In the case of manual setting, the browser can be required to store the accepted cookie on the hard disk of the client computer, and the survival time of the cookie on the hard disk needs to be specified. Within the survival time range, close the browser and close the client The computer and shutting down the server will not cause the cookie to be destroyed . When the time to live is reached, the cookie is automatically deleted from the hard disk.
cookie.setMaxAge(60);//cookie在硬盘上存活60秒。

httpsession interface

Introduction

  • From an interface under the servlet specification. Exist in the servlet-api jar package in tomcat

Related interface implementation classes are also provided by the http server, and the interface implementation classes provided by tomcat exist in the servlet-api jar package

  • If two servlets come from the same website and provide services for the same browser/user , then use the httpsession object for data sharing
  • Developers are accustomed to calling the object decorated by the httpsession interface [session scope object]

The difference between httpsession and cookie [interview questions]

  1. Different storage locations:

    One is "in the sky" and one is "underground"

cookie: exists in the client computer (browser memory/hard disk)

httpsession: stored in the memory of the server computer for days

  1. Different data types

The shared data type stored in the cookie object can only be String

The httpsession object can store any type of shared data object

  1. Number of data

A cookie object can only store one shared data (a key-value pair)

httpsession uses map collections to store shared data and can store any amount of shared data

  1. Different reference

Cookie is equivalent to the customer's [Membership Card] on the server side. The amount of data is small and the data type is single.

httpsession is equivalent to the customer’s [private safe] on the server side

Command implementation

  • Oneservlet under the same website (myweb) passes data to twoservlet
oneservlet{
	public void doget(resquest  response){
		//1.调用请求对象向tomcat索要当前用户在服务端的【私人储物柜】
		HttpSession session = request.getSession();
		//2.将数据添加到【私人储物柜中】
		session.setAttribute("key1",共享数据)
	}
}
  • Browser access twoservlet in /myweb

    twoservlet{
    	public void doget(resquest  response){
    		//1.调用请求对象向tomcat索要当前用户在服务端的【私人储物柜】
    		HttpSession session = request.getSession();
    		//2.从会话作用域对象得到onesevlet提供的共享数据
    		Object 共享数据 = session.getAttribute("key1");
    		//将session中所有的key读取出来,存放到一个枚举对象中
    		Enumeration goodnames = session.getAttributeNames();
    	}
    }
    
    

How the http server associates users with httpsession

When tomcat creates an httpsession object, it will automatically generate a unique number for the httpsession object.

tomcat saves this number in the cookie object and pushes it to the current browser cache

cookie:Jsessionid=xxxx

When the user initiates the request for the second time, tomcat confirms whether the user has httpsession and which httpsession is the current user according to the JSESSIONid in the request header

getsession()和getsession(faslse)

  • getsession(): If the current user already has his own [Private Locker] on the server, ask Tomcat to return this [Private Locker].

If the current user does not have a [private locker] on the server, tomcat is required to create a brand new private locker for the current user.

  • getsession (false): If the current user already has his own [Private Locker] on the server, ask Tomcat to return this [Private Locker].

    If the current user does not have a [Private Locker] on the server, then tomcat will return a null

Destroy timing of httpsession

  • The cookie used when the user is associated with httpsession can only be stored in the browser cache
  • When the browser is closed, it means that the user's httpsession relationship with him is cut off
  • Since tomcat cannot detect when the browser is closed, it will not cause tomcat to destroy the httpsession associated with the browser when the browser is closed.
  • In order to solve this problem, tomcat sets [idle time] for each httpsession object. The idle time is 30min by default. If the idle time of the current httpsession object reaches 30min, then tomcat thinks that the user has given up his httpsession, and then tomcat will be destroyed This httpsession

Manual setting of httpsession idle time

The maximum idle time of the current website/web/web-inf/web.xml is five minutes

<session-config>

<session-timeout>5</session-timeout>

</session-config>

httpservletrequest interface realizes data sharing

Introduction

  • If in the same website, two servlets are called by means of [request forwarding], they will share the same request protocol package with each other, and a request protocol package corresponds to only one request object, so sharing between servlets The same request object, this request object can be used to realize data sharing between the two servlets
  • When the request object realizes the data sharing function between servlets, the developer refers to the request object as [request scope object]

Command implementation

When oneservlet requests to call twoservlet through request forwarding, it needs to provide shared data to twoservlet

oneservlet{
	doget(request,response){
		//1.将数据添加到【请求作用域对象】中attribute属性
		request.setattribute("key1",数据);//数据类型可以是任意类型 object
		//2.向tomcat申请调用twoservlet
		request.getrequestdispacher("/two").forward(request,response);
	}
}


twoservlet{
	doget(request response){
		//从当前请求对象中得到oneservlet写入的共享数据
		object 数据 = request.getattribute("key1");
	}
}

Guess you like

Origin blog.csdn.net/weixin_43903813/article/details/114108820