Kirill
Kirill

Reputation: 1610

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 ?

Upvotes: 2

Views: 2879

Answers (2)

Tugalsan Karabacak
Tugalsan Karabacak

Reputation: 643

I made a working example at github.jakarta.

I just used jakarta.servlet.annotation.WebListener and contextInitialized is triggered.

I degraded from jakarta to javax for your use case github.javax

Upvotes: -1

Kirill
Kirill

Reputation: 1610

I did it using ServletContainerInitializer.

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

Upvotes: 4

Related Questions