Servlet uses annotation Listener (Listener) and servletlistener
The @ WebListener annotation provided by Servlet3.0 defines a class that implements a specific listener interface as a listener.In this way, when we use listeners in web applications, we do not need to configure the listener description in the web. xml file.
Next we will create a listener and try to use the @ WebListener annotation to mark the listener, as shown below:
The listener code is as follows:
Package me. gacl. web. listener; import javax. servlet. servletContextEvent; import javax. servlet. servletContextListener; import javax. servlet. annotation. webListener;/*** use the @ WebListener annotation to mark the listener that implements the ServletContextListener interface as the listener */@ WebListenerpublic class implements ServletContextListener {@ Override public void contextDestroyed (ServletContextEvent sce) {System. out. println ("ServletContex destruction") ;}@ Override public void contextInitialized (ServletContextEvent sce) {System. out. println ("ServletContex initialization"); System. out. println (sce. getServletContext (). getServerInfo ());}}
The listener is initialized when the Web application starts, as shown in:
With the @ WebListener annotation, no configuration is required for our web. xml.
<?xml version="1.0" encoding="UTF-8"?><web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>
The emergence of the Servlet3.0 specification allows us to develop Servlet, Filter, and Listener programs to achieve zero configuration in web. xml.