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).
}
}