gpt4 book ai didi

java - Tomcatembedded 不会抛出 FAILED LifeCycleState

转载 作者:行者123 更新时间:2023-12-01 17:21:00 24 4
gpt4 key购买 nike

我有一个像这样的休息 Jersey 应用程序

@ApplicationPath("/rest")
public class HelloApp extends Application
{
public HelloApp() throws Exception {
//also tried throwing Runtimeexcpetion
throw new Exception();
}

@Override
public Set<Class<?>> getClasses()
{
Set<Class<?>> s = new HashSet<Class<?>>();
s.add(HelloWorldService.class);
return s;
}
}

这是 web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>REST Web Application Demo</display-name>

<servlet>
<servlet-name>jersey.hello</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>rest.demo.HelloApp</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey.hello</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

</web-app>

我将上面的内容打包成war文件,然后在下面的tomcat嵌入式程序中使用

public class WarExample {

public static void main(String[] args) throws ServletException, LifecycleException {
Tomcat tomcat = new Tomcat();
tomcat.setBaseDir("temp");
tomcat.setPort(8080);

String contextPath = "/";
String warFilePath = "path to war file";
tomcat.getHost().setAppBase(".");

Context context = tomcat.addWebapp(contextPath, warFilePath);
context.addLifecycleListener(new LifecycleListener() {

public void lifecycleEvent(LifecycleEvent event) {
System.out.println(event.getLifecycle().getStateName());
//do something if event.getLifecycle().getState() == LifecycleState.FAILED
}
});
tomcat.start();
tomcat.getServer().await();

}
}

我向上下文添加了一个生命周期监听器,该上下文是通过将 war 添加为 webapp 而返回的。我正在获取“开始”和“已开始”状态,但在这里没有看到任何其他状态。即使我从我的 Jersey 休息应用程序中抛出异常/运行时异常,为什么嵌入的 tomcat 仍然没有抛出失败状态。

最佳答案

我必须添加这个以使 tomcat 发布失败状态

        final Host host = tomcat.getHost();
if (host instanceof StandardHost) {
((StandardHost) tomcat.getHost()).setFailCtxIfServletStartFails(true);
}

关于java - Tomcatembedded 不会抛出 FAILED LifeCycleState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61289835/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com