Now for the servlet listener listener, it's a server-side program that implements the Javax.servlet.ServletContextListener interface, and it's also started with web apps
Starts, initializes only once, and destroys with the Web application stopped. The main role is: To do some initialization of the content to add work, set some basic content, such as some parameters or some
Fixed objects and so on. First look at the source code for the Servletcontextlistener interface:
[Java]View plain copy public abstract interface Servletcontextlistener extends eventlistener{public abstract void cont Extinitialized (Servletcontextevent paramservletcontextevent); public abstract void contextdestroyed (Servletcontextevent paramservletcontextevent); }
The following uses the listener's initialization of the database connection pool datasource to demonstrate its use: Listenertest.java
[Java] View Plain copy import javax.servlet.servletcontext; Import javax.servlet.ServletContextEvent; import javax.servlet.servletcontextlistener; import org.apache.commons.dbcp.basicdatasource; /** * now says the servlet listener listener, which is the * server-side program that implements the javax.servlet.servletcontextlistener interface, It is also initiated with the launch of a Web application, initialized only once and destroyed with the stop of the Web application. The main role is: To do some initialization * content to add work, set some basic content, such as some parameters or some fixed objects and so on. * * Sample code: Initializing database Connection pool DataSource with listeners */ public class ListenerTest implements ServletContextListener{ // Application Listener's destruction method public void contextdestroyed (servletcontextevent servletcontextevent) { ServletContext Servletcontext = servletcontextevent.getservletcontext (); // call before the entire Web application is destroyed, emptying all of the application space servletcontext.removeattribute ("DataSource"); &NBSP;SYSTEM.OUT.PRINTLN ("Destroy work completed ..."); } // Application Listener initialization method public void contextinitialized (servletcontextevent servletcontextevent) { // Through this event can get the entire application space // Do some initialization work when the entire Web application starts under: servletcontext servletcontext = Servletcontextevent.getservletcontext (); // set some basic content, such as some parameters or some fixed objects // Create DataSource objects, connection pooling technology dbcp basicdatasource basicdatasource = new basicdatasource (); basicdatasource.setdriverclassname ("Com.jdbc.Driver"); basicdatasource.seturl ("Jdbc:mysqlocalhost : 3306/"); basicdatasource.setusername (" root ") ; <