在Struts2中咱們能夠定義全局異常而後跳轉到對用戶友好的錯誤提示頁面。在SpringMVC中咱們依然能夠。java
//在當前Handler裏寫一個處理異常的方法而且加上註解 @ExceptionHandler //value值表示能夠處理哪些異常及其子類異常 @ExceptionHandler(value = {ArithmeticException.class}) public String handExceptionForHelloAction(Exception e) { System.out.println("出異常啦!"); //定義跳轉的出錯頁面 return "error"; } //測試@ExceptionHandler異常處理 @RequestMapping("errortest") public ModelAndView testError( @RequestParam("num") int num, ModelAndView modelAndView) { System.out.println("10/" + num + "=" + 10 / num); modelAndView.addObject("msg", "Successful!"); modelAndView.setViewName("success"); return modelAndView; }
當請求方法是http://localhost:8080/SSMProjectMaven/hello/errortest.do?num=10時,測試結果以下:app
當請求方法是http://localhost:8080/SSMProjectMaven/hello/errortest.do?num=0時,測試結果以下:測試
若是咱們想要在頁面中輸出錯誤信息能夠使用ModelAndView:spa
//在當前Handler裏寫一個處理異常的方法而且加上註解 @ExceptionHandler //value值表示能夠處理哪些異常及其子類異常 @ExceptionHandler(value = {ArithmeticException.class}) public ModelAndView handExceptionForHelloAction(Exception e) { System.out.println("出異常啦!"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("exception", e.getMessage()); modelAndView.setViewName("error"); //定義跳轉的出錯頁面 return modelAndView; }
當請求方法是http://localhost:8080/SSMProjectMaven/hello/errortest.do?num=0時,測試結果以下:code
注意:這裏不能在處理異常的方法的入參里加入ModelAndView或者Map,即不能這樣:對象
寫一個處理專門處理異常的類:繼承
在類的上添加@ControllerAdvice註解get
@ControllerAdvice public class HandleAllException { @ExceptionHandler(value = {ArithmeticException.class}) public ModelAndView handExceptionForHelloAction(Exception e) { System.out.println("出異常啦!"); ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("exception", e.getMessage()); modelAndView.setViewName("error"); //定義跳轉的出錯頁面 return modelAndView; } }
在SpringMVC配置文件中要配置掃描到該類的包,我這個類是放在at.flying.exceptionhandler包中的,因此添加以下的信息:源碼
測試的方法及測試結果同上。it
• 主要處理 Handler 中用 @ExceptionHandler 註解定義的方法。
• @ExceptionHandler 註解定義的方法優先級問題:例如發
生的是NullPointerException,可是聲明的異常有
RuntimeException 和 Exception,此候會根據異常的最近
繼承關係找到繼承深度最淺的那個 @ExceptionHandler
註解方法,即標記了 RuntimeException 的方法
• ExceptionHandlerMethodResolver 內部若找不
到@ExceptionHandler 註解的話,會找
@ControllerAdvice 中的@ExceptionHandler 註解方法
採用這種方式SpringMVC會把異常對象放入request域中,key就是exceptionAttribute裏設置的值,該值默認是exception.
源碼以下:
測試方法同上,測試結果以下: