Servlet listener Listner

Keywords: Java xml Spring

Definition:

Objects specially designed to monitor and deal with events or state changes that occur on other objects, and take corresponding actions immediately when the monitored objects occur.

The Servlet specification defines an interface for each event listener, which is used to monitor the creation and destruction of domain objects such as ServletContext, HttpSession and ServletRequest in web applications.

Interface implementation class:

Event listener programs written only need to implement these interfaces

public class HelloServletContextListner 
	implements ServletContextListener, ServletRequestListener, HttpSessionListener {

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		System.out.println("ServletContext Objects are created. " + sce.getServletContext());
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		System.out.println("ServletContext Objects are destroyed." + sce.getServletContext());
	}

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		System.out.println("HttpSession Be created.");
	}
       
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		// TODO Auto-generated method stub
		System.out.println("HttpSession Be destroyed");
	}

	@Override
	public void requestDestroyed(ServletRequestEvent sre) {
		// TODO Auto-generated method stub
		System.out.println("ServletRequest Be destroyed");
	}

	@Override
	public void requestInitialized(ServletRequestEvent sre) {
		// TODO Auto-generated method stub
		System.out.println("ServletRequest Be created");
	}

}

Declare registration:

Servlet event listeners need to be registered in web.xml files of web applications

	<!-- Configure monitoring -->
	<listener>
		<listener-class>com.demo.listener.HelloServletContextListner</listener-class>
	</listener>

 

Application scenarios:

ServletContextListener is the most commonly used Listener, which can initialize the relevant resources of the current WEB application when the current WEB application is loaded: Create Spring's IOC container;

2.HttpSessionListener, Statistics of Current Online Number List

Posted by jskywalker on Tue, 29 Jan 2019 08:18:16 -0800