how2j_HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面

how2j

how2j

默认的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 @ControllercustomError处理程序方法将包装从请求中检索的信息,并将其返回到视图。

@Controller
class CustomErrorController {

 @RequestMapping("error") 
 public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
  // retrieve some useful information from the request
  Integer 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的源代码,或者更好的是,使用它生成一个新项目。

翻译自: https://www.javacodegeeks.com/2013/11/how-to-custom-error-pages-in-tomcat-with-spring-mvc.html

how2j

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值