javascript
Spring MVC错误处理流程
使用Spring MVC可以通過三種方式處理異常流,其目的是攔截任何應用程序異常,并向用戶提供友好而信息豐富的視圖。
1.在web.xml文件中使用error-page標記:
 這是servlet規范驅動的方法,其中基于HTTP響應代碼或異常類型來攔截從應用程序冒出的異常,并使用location子標記通過以下方式指定該異常的處理程序: 
如果它是基于Spring MVC的應用程序,并且意圖是通過Spring MVC視圖呈現消息,那么理想情況下,一個位置應該是可以顯示內容的Spring控制器,并且可以使用上面的2個位置來完成此操作Spring MVC配置:
<mvc:view-controller path="/500" view-name="500view"/> <mvc:view-controller path="/uncaughtException" view-name="uncaughtexception"/>2.注冊一個
HandlerExceptionResolver負責將異常映射到視圖,最簡單的方法是注冊一個SimpleMappingExceptionResolver,它可以將異常類型映射到視圖名稱。 以下是使用Spring xml bean定義(基于Roo示例)注冊SimpleMappingExceptionResolver的方法:
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" p:defaultErrorView="uncaughtException"><property name="exceptionMappings"><props><prop key=".DataAccessException">dataAccessFailure</prop><prop key=".NoSuchRequestHandlingMethodException">resourceNotFound</prop><prop key=".TypeMismatchException">resourceNotFound</prop><prop key=".MissingServletRequestParameterException">resourceNotFound</prop></props></property> </bean>或使用基于Java配置的bean定義:
@Bean public HandlerExceptionResolver handlerExceptionResolver() {SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();exceptionResolver.setDefaultErrorView("uncaughtException");Properties mappings = new Properties();mappings.put(".DataAccessException", "dataAccessFailure");mappings.put(".NoSuchRequestHandlingMethodException", "resourceNotFound");mappings.put(".TypeMismatchException", "resourceNotFound");mappings.put(".MissingServletRequestParameterException", "resourceNotFound");exceptionResolver.setExceptionMappings(mappings );return exceptionResolver; }3.使用@ExceptionHandler
這是我的首選方法,使用@ExceptionHandler批注有兩種變體。
在第一個變體中,可以將@ExceptionHandler應用于控制器類的級別,在這種情況下,同一控制器@RequestMapped方法引發的異常由@ExceptionHandler注釋方法處理。
@Controller public class AController {@ExceptionHandler(IOException.class)public String handleIOException(IOException ex) {return "errorView";} }在@ExceptionHandler的第二個變體中,可以通過對@ControllerAdvice帶注釋的類的方法進行注釋,將注釋應用于所有控制器類:
@ControllerAdvice public class AControllerAdvice {@ExceptionHandler(IOException.class)public String handleIOException(IOException ex) {return "errorView";} } 這些本質上是在Spring MVC應用程序中處理應用程序異常的方法。 
翻譯自: https://www.javacodegeeks.com/2013/06/spring-mvc-error-handling-flow.html
總結
以上是生活随笔為你收集整理的Spring MVC错误处理流程的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: 怎么设置国旗渐变头像
 - 下一篇: 动态初音桌面壁纸电脑(初音电脑壁纸动态壁