11

I would like to perform some action as soon as my application (Enterprise Application with Business Logic, EJB, and a Client, Web) is deployed. For example I would like to make some entity in a persistent state, or otherwise create a file. How can I do that?

Thanks.

bdoughan
  • 147,609
  • 23
  • 300
  • 400
Mauro
  • 361
  • 1
  • 4
  • 14

3 Answers3

15

Configure SerlvetContextListener and override contextInitilized()

in your web application description , web.xml

<web-app ...>
    <listener>
        <listener-class>com.someCompany.AppNameServletContextListener</listener-class>
    </listener>
</web-app

package com.someCompany;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class AppNameServletContextListener implements ServletContextListener{

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("ServletContextListener destroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("ServletContextListener started");   
                // do the things here 
    }
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • Thanks a lot! Well... I'm a little newbie with JEE. How can I configure a ContextListener? – Mauro May 25 '11 at 07:22
  • @Mauro hit F5 , added information – jmj May 25 '11 at 07:23
  • Thank you so much! I'm going to try that... I'll let you know. – Mauro May 25 '11 at 07:34
  • 1
    **Even Easier Now…** The [@WebListener](http://docs.oracle.com/javaee/7/api/javax/servlet/annotation/WebListener.html) annotation added to [Servlet 3.0 spec](https://jcp.org/en/jsr/detail?id=315) now gives you this behavior without the bother of editing the *web.xml* file. See this illuminating [answer by BalusC](http://stackoverflow.com/a/9186070/642706). – Basil Bourque Feb 23 '14 at 11:14
0

The "default" way is to have a servlet with an init() method. Then in the servlet-descriptor you mark this servlet as load-on-startup 1:

Example:

<servlet-name>Seam Resource Servlet</servlet-name>
   <servlet-class>org.jboss.seam.servlet.SeamResourceServlet</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

As soon as the servlet is deployed (which happens after the EJBs are deployed), that init() method is called and you can execute the task you want.

Heiko Rupp
  • 30,426
  • 13
  • 82
  • 119
0

With present web application in your ear, the easiest and simplest would be to use ServletContextListener, otherwise in EJB 3.1 you could use automatic timers or startup singleton session beans.

Kris
  • 5,714
  • 2
  • 27
  • 47