這篇文章描述了在Spring MVC 3中執行錯誤處理的不同技術。該代碼在GitHub上的Spring-MVC-Error-Handling目錄中可用。 它基于帶有注釋的Spring MVC示例。
在Spring 3之前處理異常
在Spring 3之前,使用HandlerExceptionResolvers處理異常。 此接口定義一個方法:
ModelAndView resolveException(HttpServletRequest request,HttpServletResponse response,Object handler,Exception ex)
注意,它返回一個ModelAndView對象。 因此,遇到錯誤意味著將被轉發到特殊頁面。 但是,此方法不適用于REST Ajax對JSON的調用(例如)。 在這種情況下,我們不想返回頁面,我們可能想返回特定的HTTP狀態代碼。 提供了進一步描述的解決方案。
為了本示例的緣故,已經創建了兩個假的CustomizedException1和CustomizedException2異常。 要將自定義的異常映射到視圖,可以(并且仍然可以)使用impleMappingExceptionResolver :
SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {SimpleMappingExceptionResolver result= new SimpleMappingExceptionResolver();// Setting customized exception mappingsProperties p = new Properties();p.put(CustomizedException1.class.getName(), 'Errors/Exception1');result.setExceptionMappings(p);// Unmapped exceptions will be directed thereresult.setDefaultErrorView('Errors/Default');// Setting a default HTTP status coderesult.setDefaultStatusCode(HttpStatus.BAD_REQUEST.value());return result;}
我們將CustomizedException1映射到Errors / Exception1 JSP頁面(視圖)。 我們還為未映射的異常設置了默認錯誤視圖,在此示例中為CustomizedException2。 我們還設置了默認的HTTP狀態代碼。
這是Exception1 JSP頁面,默認頁面與此類似:
<%@page contentType='text/html' pageEncoding='UTF-8'%>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!doctype html>
<html lang='en'>
<head><meta http-equiv='Content-Type' content='text/html;' charset=UTF-8'><title>Welcome To Exception I !!!</title>
</head>
<body><h1>Welcome To Exception I !!!</h1>Exception special message:<${exception.specialMsg}<a href='<c:url value='/'/>'>Home</a>
</body>
</html>
我們還創建了一個虛擬錯誤控制器來幫助觸發這些異常:
@Controller
public class TriggeringErrorsController {@RequestMapping(value = '/throwCustomizedException1')public ModelAndView throwCustomizedException1(HttpServletRequest request,HttpServletResponse response)throws CustomizedException1 {throw new CustomizedException1('Houston, we have a problem!');}@RequestMapping(value = '/throwCustomizedException2')public ModelAndView throwCustomizedException2(HttpServletRequest request,HttpServletResponse response)throws CustomizedException2 {throw new CustomizedException2('Something happened on the way to heaven!');}...}
在Spring 3之前,將在Web.xml中將SimpleMappingExceptionResolver聲明為@Bean。 但是,我們將使用HandlerExceptionResolverComposite,稍后將對其進行描述。
我們還在web.xml中為HTTP狀態代碼配置目標頁面,這是處理問題的另一種方法:
<error-page><error-code>404</error-code><location>/WEB-INF/pages/Errors/My404.jsp</location>
</error-page>
從Spring 3.X開始有什么新功能?
@ResponseStatus批注是在調用方法時設置Http狀態代碼的新方法。 這些由ResponseStatusExceptionResolver處理。 @ExceptionHandler注釋有助于在Spring中處理異常。 此類注釋由AnnotationMethodHandlerExceptionResolver處理。
下面說明了如何在觸發我們的自定義異常時使用這些注釋將HTTP狀態代碼設置為響應。 該消息在響應的正文中返回:
@Controller
public class TriggeringErrorsController {...@ExceptionHandler(Customized4ExceptionHandler.class)@ResponseStatus(value=HttpStatus.BAD_REQUEST)@ResponseBodypublic String handleCustomized4Exception(Customized4ExceptionHandler ex) {return ex.getSpecialMsg();}@RequestMapping(value = '/throwCustomized4ExceptionHandler')public ModelAndView throwCustomized4ExceptionHandler(HttpServletRequest request,HttpServletResponse response)throws Customized4ExceptionHandler {throw new Customized4ExceptionHandler('S.O.S !!!!');}}
在用戶端,如果使用Ajax調用,則可以使用以下方法(我們正在使用JQuery)來檢索錯誤:
$.ajax({type: 'GET',url: prefix + '/throwCustomized4ExceptionHandler',async: true,success: function(result) {alert('Unexpected success !!!');},error: function(jqXHR, textStatus, errorThrown) {alert(jqXHR.status + ' ' + jqXHR.responseText);}
});
一些使用Ajax的人喜歡返回帶有錯誤代碼的JSON和一些用于處理異常的消息。 我覺得這太過分了。 一個簡單的錯誤號和一條消息使其保持簡單。
由于我們使用了多個解析器,因此我們需要一個復合解析器(如前所述):
@Configuration
public class ErrorHandling {...@BeanHandlerExceptionResolverComposite getHandlerExceptionResolverComposite() {HandlerExceptionResolverComposite result= new HandlerExceptionResolverComposite();List<HandlerExceptionResolver> l= new ArrayList<HandlerExceptionResolver>();l.add(new AnnotationMethodHandlerExceptionResolver());l.add(new ResponseStatusExceptionResolver());l.add(getSimpleMappingExceptionResolver());l.add(new DefaultHandlerExceptionResolver());result.setExceptionResolvers(l);return result;}
DefaultHandlerExceptionResolver解析標準的Spring異常并將其轉換為相應的HTTP狀態代碼。
運行示例
編譯后,可以使用mvn tomcat:run運行該示例。 然后,瀏覽:
http:// localhost:8585 / spring-mvc-error-handling /
主頁將如下所示:
如果單擊“例外1”鏈接,將顯示以下頁面:
如果單擊“例外2”鏈接,將顯示以下頁面:
如果單擊“異常處理程序”按鈕,將顯示一個彈出窗口:
這些技術足以涵蓋Spring中的錯誤處理。
更多春天相關的帖子在這里 。
參考: 技術說明博客上來自JCG合作伙伴 Jerome Versrynge的Spring MVC錯誤處理 。
翻譯自: https://www.javacodegeeks.com/2012/11/spring-mvc-error-handling-example.html