javatomcatservletstomcat8servletcontextlistener

How to add ServletContextListener in embedded tomcat


I have a simple application with embedded tomcat. And I trying to do some initialization work and I need JNDI resources.

I trying to do it in ServletContextListener.contextInitialized.

When I add ServletContextListener before tomcat.start(), context.getServletContext() returns null.

If I doing it after tomcat.start(), I got an error:

Exception in thread "main" java.lang.IllegalStateException: Listeners cannot be added to context [] as the context has been initialised

This is launcher code:

public static void main(String[] args) throws Exception {
    Tomcat server = new Tomcat();
    server.setPort(8080);

    Context context = server.addContext("", Paths.get(".").toAbsolutePath().toString());

    Tomcat.addServlet(context, "hello", new HelloServlet());
    context.addServletMappingDecoded("/", "hello");

    ContextResource resource = buildResource(
        H2_DATA_SOURCE_NAME,
        DataSource.class.getName(),
        h2DatasourceProperties()
    );

    context.getNamingResources().addResource(resource);
    context.getServletContext().addListener(DataBaseSchemaInit.class);

    server.start();
    server.getServer().await();
}

How can I add ServletContextListener in embedded tomcat v.8.5.28 ?


Solution

  • I did it using ServletContainerInitializer.

    StandardContext context = buildContext(tomcat);
    ...
    context.addServletContainerInitializer(new DataBaseInitializer(DATA_BASE_SCHEMA), null);