- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我们有几个使用 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
最佳答案
如果您的 Tomcat 服务器前面有某种代理(如 apache 或 nginx ),我相信它可以配置为将 404 转换为不同的状态代码和错误页面。如果您没有任何代理或希望解决方案保持独立:
由于您使用的是 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/
我是一名优秀的程序员,十分优秀!