日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

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

發布時間:2023/12/3 javascript 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

默認的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

總結

以上是生活随笔為你收集整理的HOW-TO:带有Spring MVC的Tomcat中的自定义错误页面的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。