當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面
生活随笔
收集整理的這篇文章主要介紹了
HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
默認的Tomcat錯誤頁面看起來很可怕。 此外,它們可能會公開有價值的信息,包括服務器版本和異常堆棧跟蹤。 Servlet規范提供了一種通過web.xml配置異常行為的方法。 可以配置對特定Java異常的響應,也可以配置對選定的Http響應代碼的響應。
error-page元素指定錯誤代碼或異常類型與Web應用程序中資源路徑之間的映射:
在我們的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的源代碼,或者更好的方法是使用它生成一個新項目。
翻譯自: https://www.javacodegeeks.com/2013/11/how-to-custom-error-pages-in-tomcat-with-spring-mvc.html
總結
以上是生活随笔為你收集整理的HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 三星手机的屏幕投屏到电脑(三星手机投屏到
- 下一篇: 使用Spring Form标签探索Spr