What is Listener?
Listener is something sitting there and wait for specified event happened, then “hijack” the event and run it’s own event.
ServletContextListener is a interface which contains two methods:
2) Put it in deployment descriptor
Let’s say…
You want to initialize the database connection pool before the web application is start, is there a “main()” method in whole web application?Solution
The “ServletContextListener” is what you want. It will make your code run before the web application is start.ServletContextListener is a interface which contains two methods:
- public void contextInitialized(ServletContextEvent event)
- public void contextDestroyed(ServletContextEvent event)
package com.mkyong; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class AppServletContextListener implements ServletContextListener{ @Override public void contextDestroyed(ServletContextEvent arg0) { System.out.println("ServletContextListener destroyed"); } @Override public void contextInitialized(ServletContextEvent arg0) { System.out.println("ServletContextListener started"); } }
<web-app ...> <listener> <listener-class>com.mkyong.AppServletContextListener</listener-class> </listener> </web-app>
No comments:
Post a Comment