默认的Tomcat错误页面看起来很可怕。 此外,它们可能会公开有价值的信息,包括服务器版本和异常堆栈跟踪。 Servlet规范提供了一种通过web.xml配置异常行为的方法。 可以配置对特定Java异常的响应,也可以配置对选定的Http响应代码的响应。
error-page
元素指定错误代码或异常类型与Web应用程序中资源路径之间的映射:
<web-app><!-- Prior to Servlet 3.0 define either an error-code or an exception-type but not both --><error-page><!-- Define error page to react on Java exception --><exception-type>java.lang.Throwable</exception-type><!-- The location of the resource to display in response to the error will point to the Spring MVC handler method --><location>/error</location></error-page><error-page><error-code>404</error-code><location>/error</location></error-page><!-- With Servlet 3.0 and above general error page is possible --><error-page><location>/error</location></error-page></web-app>
在我们的web.xml中定义了自定义错误页面后,我们需要添加Spring MVC @Controller
。 customError
处理程序方法包装我们从请求中检索的信息,并将其返回到视图。
@Controller
class CustomErrorController {@RequestMapping("error") public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {// retrieve some useful information from the requestInteger statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception");// String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");String exceptionMessage = getExceptionMessage(throwable, statusCode);String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");if (requestUri == null) {requestUri = "Unknown";}String message = MessageFormat.format("{0} returned for {1} with message {3}", statusCode, requestUri, exceptionMessage); model.addAttribute("errorMessage", message); return "customError";}private String getExceptionMessage(Throwable throwable, Integer statusCode) {if (throwable != null) {return Throwables.getRootCause(throwable).getMessage();}HttpStatus httpStatus = HttpStatus.valueOf(statusCode);return httpStatus.getReasonPhrase();}
}
产生的消息可能如下所示: 404 returned for /sandbox/bad with message Not Found
。
要查看运行中的代码,请浏览Spring MVC Quickstart Archretype的源代码,或者更好的方法是使用它生成一个新项目。
参考:操作方法 :来自JCG合作伙伴 Rafal Borowiec的Spring MVC在Tomcat中的自定义错误页面,位于Codeleak.pl博客上。
翻译自: https://www.javacodegeeks.com/2013/11/how-to-custom-error-pages-in-tomcat-with-spring-mvc.html