Listener three: ServletContext, HttpSession, HttpServletRequest three built-in object listeners; three built-in object attribute listeners;

 This blog mainly introduces: the application of the listener to the creation and destruction of three built-in objects; the addition and deletion of attributes in the built-in objects;

table of Contents

One: Introduction

Two: listeners for three built-in objects (the creation and destruction of built-in objects)

1. Case content:

First, write a Servlet: HelloServlet:

Then, write the listener class: WebListener:

Finally, configure the listener in web.xml:

2. Start the application and observe the effect:

First, open the browser and initiate a request:

Then, close the browser window and re-initiate the request:

For example, if you do not close the browser window, but refresh the interface:

Finally, close the application:

Three: Attribute Listener (addition and deletion of built-in object attributes) (Attribute Listener is not used much in practice)

1. Preparation; adding attributes

2. Attribute update; delete (the two are less used, just have an impression first)


One: Introduction

Six commonly used interfaces in the listener: object monitoring interface; attribute monitoring interface (in the object):

If you are not sure about the three built-in objects, you can check the blog of JavaWeb Three Scope Objects ;


Two: listeners for three built-in objects (the creation and destruction of built-in objects)

The second part is mainly to show that the listener can monitor "object creation" and "object destruction";;; Mainly observe the whole process!

1. Case content:

First, write a Servlet: HelloServlet :

In this Servlet, the attributes of the three objects ServletContext, HttpSession, and HttpServletRequest are set;

package com.imooc.listener;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet
 */
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().println("This is HelloSerrvler!");
		// 得到应用程序全局对象;并在其中设置一个属性;
		request.getServletContext().setAttribute("sc-attr1", "sc-attr-value1");
		// 得到用户会话对象;并在其中设置一个属性;
		request.getSession().setAttribute("session-attr1", "session-attr-value1");
		// 在请求对象中设置一个属性;
		request.setAttribute("request-attr1", "request-attr-value1");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

Then, write the listener class: WebListener :

Three interfaces, ServletContextListener, HttpSessionListener, and ServletRequestListener are implemented, and each interface has two methods to be implemented (create and destroy operations respectively)

package com.imooc.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * WebListener类实现ServletContextListener接口,以使该监听器类可以监听ServletContext对象;
 * WebListener类实现HttpSessionListener接口,以使该监听器类可以监听HttpSession对象;
 * WebListener类实现ServletRequestListener接口,以使该监听器类可以监听ServletRequest对象;
 * @author Administrator
 *
 */
public class WebListener implements ServletContextListener,HttpSessionListener,ServletRequestListener{

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("ServletContext已经被销毁。");
		
	}

	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("ServletContext已经被初始化。");
		
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		// TODO Auto-generated method stub
		// se:HttpSessionEvent对象(即HttpSession事件对象),这个se参数可以调用方法,获取到已经被创建的Session对象;
		HttpSession session = se.getSession();
		System.out.println("Session已经被创建,SessionID为:"+session.getId());
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("Session已经被销毁。");
	}

	@Override
	public void requestDestroyed(ServletRequestEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("HttpServletRequest请求对象已经被销毁。");
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		// TODO Auto-generated method stub
		// sre可以获取ServletRequest请求对象,这儿需要强转一下,转成HttpServletRequest类型的;
		HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
		System.out.println("HttpServletRequest请求对象已经被创创建,uri是:"+request.getRequestURI());
		
	}

}

Finally, configure the listener in web.xml :

2. Start the application and observe the effect:

First, open the browser and initiate a request:

And open the browser, access the above Servlet: In this process, a request is initiated, an HttpServletRequest object will be created; naturally this is a session is opened, and an HttpSession object will also be created; (For details, see: Session object blog Session principle explanation part)

When accessing the address localhost:8080/listener-interface/hello, an HttpServletRequest object will be created;;; Because this is a request from a new browser window, Tomcat will create a new Session object for it ;;;; Immediately after the Servlet processing is completed, along with the output of the response, the HttpServletRequest object created just now is destroyed;;; (These creation and destruction processes will naturally trigger the corresponding methods in the listener)

Then, close the browser window and re-initiate the request:

If at this time, close the browser and revisit localhost:8080/listener-interface/hello:

When the browser window is closed, it will not trigger the destruction of the Session object. This is because the client is closed, but the SessionnId credential for client communication does not exist, and the Session object that exists on the server still exists (automatically after 30min) Expires, or manually call Session destruction method to destroy it):

For example, if you do not close the browser window, but refresh the interface:

Finally, close the application:

   

……………………………………………………

doubt? ? ? ? ? ? Why, when the application is closed, the method of destroying the Session is not called? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? , After the solution, come back to make up. . .


Three: Attribute Listener (addition and deletion of built-in object attributes) (Attribute Listener is not used much in practice)

Note: The attribute monitoring interface is not used much in actual projects, so here is a general understanding .

1. Preparation; adding attributes

Write attribute listener: WebAttributeListener: In the attribute interface of each object, you need to implement the Add method; the Removed method; the Replaced method;

package com.imooc.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class WebAttributeListener implements ServletContextAttributeListener,HttpSessionAttributeListener,ServletRequestAttributeListener{

	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {
		// TODO Auto-generated method stub
		// event.getName();  // 用于获取新增属性的名称;
		// event.getValue();// 获取新增属性的值;
		System.out.println("ServletContext对象新增属性了。"+event.getName()+":"+event.getValue());
	}

	@Override
	public void attributeRemoved(ServletContextAttributeEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void attributeReplaced(ServletContextAttributeEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		System.out.println("HttpSession对象新增属性了。"+event.getName()+":"+event.getValue());
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void attributeAdded(ServletRequestAttributeEvent event) {
		// TODO Auto-generated method stub
		System.out.println("HttpServletRequest对象新增属性了。"+event.getName()+":"+event.getValue());
		
	}

	@Override
	public void attributeRemoved(ServletRequestAttributeEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void attributeReplaced(ServletRequestAttributeEvent event) {
		// TODO Auto-generated method stub
		
	}

}

Configure the listener in web.xml:

Start the application: visit localhost:8080/listener-interface/hello:

……………………………………………………

2. Attribute update; delete (the two are less used, just have an impression first)

Attribute update: naturally, connect, when you have already visited localhost:8080/listener-interface/hello, refresh the interface again (that is, visit localhost:8080/listener-interface/hello again), this process will naturally re-execute the Servlet In the statement to assign a value to an object in the object, this copy of the attribute is to modify the value:

………………………………

Attribute deletion: In order to demonstrate the effect, add a statement to delete the attribute in the Servlet; then add an output statement in the delete method of the listener:

effect:

Guess you like

Origin blog.csdn.net/csucsgoat/article/details/114366039