我有一个带有嵌入式 tomcat 的简单应用程序。我尝试做一些初始化工作,并且需要 JNDI 资源。
我尝试在 ServletContextListener.contextInitialized
中执行此操作。
当我在 tomcat.start()
之前添加 ServletContextListener
时,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
?
最佳答案
我使用ServletContainerInitializer
做到了。
StandardContext context = buildContext(tomcat);
...
context.addServletContainerInitializer(new DataBaseInitializer(DATA_BASE_SCHEMA), null);
关于java - 如何在嵌入式tomcat中添加ServletContextListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49195295/