我们有几个使用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
发布于 2012-05-15 04:06:24
HTTP代理
如果您的Tomcat服务器前面有某种类型的代理(如apache或nginx),我相信它可以配置为将404转换为不同的状态代码和错误页面。如果您没有任何代理或希望解决方案保持自包含:
自定义Spring加载器和servlet过滤器
因为您使用的是Spring,所以我猜您是在web.xml中使用ContextLoaderListener引导它
<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());
        }
    }
}将此过滤器映射到所有请求(或者可能只有控制器?):
<filter-mapping>
    <filter-name>failSafeFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>解决方案可能不是你想要的,但我给你一个通用的,有效的例子。
https://stackoverflow.com/questions/10589871
复制相似问题