Saturday, October 26, 2013

Do Something on Server Startup/Shutdown


Simple Note

Code

TestServletContextListener.java

Simply output message to console while server startup/shutdown.

package test;

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

public class TestServletContextListener implements ServletContextListener {
    // do something on server shutdown
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("On server shutdown");
    }
    // do something on server startup
    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("On server startup");
    }
}


web.xml

Define listener.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>DoStOnServerStartupOrShutdown</display-name>
  <!-- Define Listener -->
  <listener>
    <listener-class>test.TestServletContextListener</listener-class>
  </listener>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>


References

Servlet Filters and Event Listeners
http://docs.oracle.com/cd/B14099_19/web.1012/b14017/filters.htm

Debug ServletContextListener.contextDestroyed() by setting the breaking point in eclipse
http://stackoverflow.com/questions/8802457/debug-servletcontextlistener-contextdestroyed-by-setting-the-breaking-point-in

Download

Full project at github
https://github.com/benbai123/JSP_Servlet_Practice/tree/master/Practice/BasicServletPractice/Projects/DoStOnServerStartupOrShutdown

No comments:

Post a Comment