java - Tomcat - 当应用程序未正确部署时如何获取 http 500 而不是 404?

标签 java tomcat deployment http-status-codes

我们有几个使用 Spring MVC 的 REST 应用程序。部署后有时某些应用程序不会启动。当我们的 Javascript 客户端尝试访问资源 url 时,它会收到 404 状态代码。因此它假定该资源不存在。更适合我们的是在 Tomcat 响应中返回 http 状态 500。是否可以更改此默认 Tomcat 行为?

我在 JBoss(使用嵌入式 Tomcat)中发现了类似的问题,但没有答案: https://serverfault.com/questions/367986/mod-jk-fails-to-detect-error-state-because-jboss-gives-404-not-500

最佳答案

HTTP 代理

如果您的 Tomcat 服务器前面有某种代理(如 ),我相信它可以配置为将 404 转换为不同的状态代码和错误页面。如果您没有任何代理或希望解决方案保持独立:

自定义 Spring 加载器和 servlet 过滤器

由于您使用的是 Spring,我猜您正在使用 ContextLoaderListener 引导它在 web.xml 中:

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

这个类负责引导 Spring,这是大多数情况下导致应用程序启动失败的步骤。只需扩展该类并吞下任何异常,这样它就永远不会到达 servlet 容器,因此 Tomcat 不会认为您的应用程序部署失败:

public class FailSafeLoaderListener extends ContextLoaderListener {

    private static final Logger log = LoggerFactory.getLogger(FailSafeLoaderListener.class);

    @Override
    public void contextInitialized(ServletContextEvent event) {
        try {
            super.contextInitialized(event);
        } catch (Exception e) {
            log.error("", e);
            event.getServletContext().setAttribute("deployException", e);
        }
    }
}

代码非常简单 - 如果 Spring 初始化失败,记录异常并将其全局存储在 ServletContext 中。新加载器必须替换 web.xml 中的旧加载器:

<listener>
    <listener-class>com.blogspot.nurkiewicz.download.FailSafeLoaderListener</listener-class>
</listener>

现在您所要做的就是在全局过滤器中从 servlet 上下文中读取该属性,并在应用程序无法启动 Spring 时拒绝所有请求:

public class FailSafeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}

    @Override
    public void destroy() {}

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        Exception deployException = (Exception) request.getServletContext().getAttribute("deployException");
        if (deployException == null) {
            chain.doFilter(request, response);
        } else {
            ((HttpServletResponse) response).sendError(500, deployException.toString());
        }
    }
}

将这个过滤器映射到所有请求(或者可能只是 Controller ?):

<filter-mapping>
    <filter-name>failSafeFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

解决方案可能不是您想要的,但我为您提供了一个通用的、可行的示例。

关于java - Tomcat - 当应用程序未正确部署时如何获取 http 500 而不是 404?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10589871/

相关文章:

deployment - 如何集中整个网站引擎?

java - LibGDX - batch.begin(); 之间有什么不同?和 renderer.getBatch().begin();?

git - 在哪里存储持续集成 (CI) 部署的私钥?

java - 何时使用新的缓存名称?

security - Tomcat 7 - 多个安全约束不起作用

java - 上传的文件保存在服务器的什么位置?

tomcat - 为什么 Grail App war 文件与源代码相比体积太大

IOS 11.3 通用应用程序部署错误 : "Invalid Bundle. Your app supports Multitasking on iPad, so you must include the UILaunchStoryboardName"

java - 连接池中的 Tomcat-Mysql 连接在空闲时间后超时

java - Set中的重复值异常