如何在嵌入式tomcat中添加ServletContextListener

时间:2018-03-09 13:51:38

标签: java tomcat servlets tomcat8 servletcontextlistener

我有一个嵌入式tomcat的简单应用程序。我尝试做一些初始化工作,我需要JNDI资源。

我尝试在ServletContextListener.contextInitialized中完成。

当我在ServletContextListener之前添加tomcat.start()时,context.getServletContext()会返回null

如果我在tomcat.start()之后这样做,我收到了一个错误:

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

这是启动码:

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();
}

如何在嵌入式tomcat v.8.5.28中添加ServletContextListener

1 个答案:

答案 0 :(得分:2)

我是使用ServletContainerInitializer完成的。

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