Listener 2: The first example of a listener;

table of Contents

Three elements of the listener:

Example of the first listener:

Listener, in the form of annotations:


Three elements of the listener:

(1) If you want a class to become a listener, and what object you want to monitor, let this class implement different corresponding interfaces;


Example of the first listener:

Create a new project and create the FirstListener class. If you want this class to become a listener, and the ServletContext object is monitored, this class needs to implement the ServletContextListener interface :

FirstListener: listener class

package com.imooc.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 * 如果想让这个类,想实现对ServletContext进行监听的时候,这个类就需要实现ServletContextListener接口
 * @author Administrator
 *
 */
public class FirstListener implements ServletContextListener{

	/**
	 * contextDestroyed:这个方法,对象销毁的时候,会触发的后续操作;
	 */
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("ServletContext已经被销毁");
	}

	/**
	 * contextInitialized:这个方法,对象初始化的时候,会触发的后续操作;
	 */
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		// TODO Auto-generated method stub
		System.out.println("ServletContext已经初始化。");
		
	}

}

Configure the listener in web.xml: the configuration of the listener is very simple, just a label

effect:

Start the application: After starting the application, the ServletContext global object is created. After the object is created, the contextInitialized() initialization method in the listener of FirstListener, which is used to monitor the ServletContext object, is triggered; (ServletContext is the global object in It will be initialized when the application starts)

Close the application: the contextDestroyed() destruction method in FirstListener, the listener used to monitor the ServletContext object, is triggered;

It can be found that we let a class implement the interface above, and then after configuring in web.xml, the listener will take effect; ;; The work behind it, Tomcat does it for us; so the original sentence, the listener is JEE Servlet A component under the module;;;; A lot of basic work does not require programmers to do, all we have to do is to call various APIs, which greatly simplifies the difficulty of development;


Listener, in the form of annotations:

Guess you like

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