1
votes

I want a method (or some functionality) to be executed after my web application starts (context loaded). I am using spring 3.0 as framework.

I tried using ServletContextListener which I implemented in my class

my listener class

package myapp.listner;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyContextListner implements ServletContextListener{

    public static long appStart=0L;
    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("Context Destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        appStart=System.currentTimeMillis();
        System.out.println("Context Initialised");

    }

}

and part of web.xml is

<listner>
     <listner-class>myapp.listner.MyContextListner</listner-class>
    </listner>

    <servlet>
      <servlet-name>dispatcher</servlet-name>

      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
      <servlet-name>dispatcher</servlet-name>
      <url-pattern>/forms/*</url-pattern>
    </servlet-mapping>

but its not printing that message.....

Please help me....

1
While I'd lean towards a Spring-oriented solution, are you sure you're looking in the right place? And is the misspelling of "listener" intentional, particularly in web.xml? It's best to cut-and-paste examples to avoid red herrings. It works fine for me. - Dave Newton

1 Answers

4
votes

PostConstruct and PreDestroy annotations, something like this :

@Configuration
public class MyConfig{

    @PostConstruct
    public void contextInitialized(){
      System.out.println("Context Initialised");
    }

    @PreDestroy
    public void contextdestroyed(){
      System.out.println("Context Destroyed");
    }
}

You don't have to use in configuration bean, it can be anywhere.