1

Possible Duplicate:
Java EE Enterprise Application: perform some action on deploy/startup

Is there a way to define something like a on load method for a javaEE ear server application.

For example I use Hibernate on a JBoss EAR Server which needs one SessionFactory instance for the whole application lifetime.

Community
  • 1
  • 1
djmj
  • 5,579
  • 5
  • 54
  • 92

1 Answers1

2

Use either a ServletContextListener

@WebListener
public class Config implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Do stuff during webapp's startup.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // Do stuff during webapp's shutdown.
    }

}

or a Filter (particularly useful if you plan to implement "open session in view" pattern)

@WebFilter("*.xhtml") // Or whatever URL pattern
public class OpenSessionInViewFilter implements Filter {

    @Override
    public void init(FilterConfig config) throws ServletException {
        // Do stuff during filter's init (so, during webapp's startup).
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        // Do stuff during every request on *.xhtml (or whatever URL pattern)
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // Do stuff during filter's destroy (so, during webapp's shutdown).
    }

}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555