Introduction to listener

When a web application runs in a web container, various events will continuously occur inside the web application: such as the web application is started, the
web application is stopped, the user session starts, the user session ends, the user request arrives, etc. Generally speaking, these Web events
are transparent to developers.

In fact, the Servlet API provides a number of monitors to monitor the internal events of the Web application, thus allowing methods in the event monitor to be called back when a Web internal event occurs.

Using the Listener only requires two steps.

  1. Define the Listener implementation class.
  2. Configure the Listener through annotations or in the web.xml file.

1. Implement the Listener class

Similar to AWT event programming, the listeners for different events are not the same. Commonly used Web event monitor connections are as follows.

"ServletContextListener: Used to monitor the startup and shutdown of Web applications.
"ServletContextAttributeListener: used to monitor changes in attributes within the ServletContext scope (application).

"ServletRequestListener: used to monitor user requests.
"ServletRequestAttributeListener: Used to monitor changes in attributes within the ServletRequest scope (request).
"HttpSessionListener: used to monitor the start and end of the user's session.
"HttpSessionAttributeListener: used to monitor changes in attributes within the scope of the HttpSession (session).

Let's take ServletContextListener as an example to introduce the development and use of Listener. ServletContextListener is used to monitor

Startup and shutdown of web applications. The Listener class must implement the ServletContextListener interface, which contains the following two methods.
》contextlnitialized(ServletContextEvent see): When starting the Web application, the system calls this method of Listener.

》contextDestroyed(ServletContextEvent see): When closing the Web application, the system calls this method of Listener.
Through the above introduction, it is not difficult to see that the role of ServletContextListener is somewhat similar to load-on-startup Servlet, which can be used to start some background programs by callback method when the Web application starts, and these background programs are responsible for providing support for system operation. .

package listener;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class GetConnListener implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        ServletContext application = sce.getServletContext();
        Connection conn = (Connection) application.getAttribute("conn");
        if(conn != null) {
            
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace ();
            }
            
        }
    }

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        try {
            
            ServletContext application = sce.getServletContext();
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hello?serverTimezone=UTC&useSSL=false", "root", "lidian1234");
            application.setAttribute("conn", conn);
            System.out.println( "Database connection is successful" );
            
        } catch (Exception e) {
            e.printStackTrace ();
        }
        
    }

}

The bold code in the above program rewrites the contextlnitialized() and contextDestroyed() methods of ServletContextListener, which are triggered when the application starts and closes, respectively. The above two methods of ServletContextListener respectively implement the functions of acquiring and closing database connections, all of which provide services for the entire Web application.
In the program, the bold code in the contextlnitialized() method is used to obtain configuration parameters. Careful readers may have found that the ServletContextListener obtains the configuration parameters of the Web application, not the configuration parameters of Serviet and Filter. This is because the configuration of the Listener is very simple, as long as the Listener implementation class is simply specified, and the initialization parameters cannot be configured.

2. Configure Listener

Configuring the Listener is as simple as registering the Listener implementation class with the web application, no configuration parameters or anything like that. There are also two ways to configure Listeners for web applications.

"Use @WebListener to decorate the Listener implementation class.
"Use the <listener.. ./> element for configuration in the web.xml document.
When using @WebListener, there is usually no need to specify any properties, as long as the Listener implementation class is modified with this annotation, the listener can be registered with the Web application.

When using the <listener.. ./> element for configuration in web.xml, you only need to configure the following sub-elements.

"listener-class: Specifies the Listener implementation class.

 

<!-- 指定listener的实现类 -->
  <listener>
      <listener-class>listener.GetConnListener</listener-class>
  </listener>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324701677&siteId=291194637