一、定義一個統一異常處理類java
@ControllerAdvice public class ExptionTest { @ExceptionHandler(Exception.class) @ResponseBody public Object exp(Exception exception){ Map<String, Object> map = new HashMap<String, Object>(); map.put("error", "頂層錯誤處理"); map.put("errorInfo", exception); map.put("errorInfo2", exception.getMessage()); StringWriter s = new StringWriter(); PrintWriter pw=new PrintWriter(s); exception.printStackTrace(pw); map.put("errorInfo3", s.toString()); return map; } @ModelAttribute public User newUser() { System.out.println("============應用到全部@RequestMapping註解方法,在其執行以前把返回值放入Model"); return new User(); } @InitBinder public void initBinder(WebDataBinder binder) { System.out.println("============應用到全部@RequestMapping註解方法,在其執行以前初始化數據綁定器"); } }
@ControllerAdvice,是spring3.2提供的新註解, 通常掃描<context:component-scan>掃描時也能掃描到,不須要在配置文件配置web
但若是你的spring-mvc配置文件使用以下方式掃描beanspring
<context:component-scan base-package="com.sishuok.es" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
須要把 @ControllerAdvice包含進來,不然不起做用:express
<context:component-scan base-package="com.sishuok.es" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
一、@ModelAttribute註解的方法做用請參考 SpringMVC強大的數據綁定(2)——第六章 註解式控制器詳解——跟着開濤學SpringMVC 中的【2、暴露表單引用對象爲模型數據】,做用是同樣的,只不過此處是對全部的@RequestMapping註解的方法都起做用。當須要設置全局數據時比較有用。spring-mvc
二、@InitBinder註解的方法做用請參考 SpringMVC數據類型轉換——第七章 註解式控制器的數據驗證、類型轉換及格式化——跟着開濤學SpringMVC ,同1相似。當須要全局註冊時比較有用。mvc
三、@ExceptionHandler,異常處理器,此註解的做用是當出現其定義的異常時進行處理的方法,其可使用springmvc提供的數據綁 定,好比注入HttpServletRequest等,還能夠接受一個當前拋出的Throwable對象。能夠參考javadoc或snowolf的 Spring 註解學習手札(八)補遺——@ExceptionHandler 。app
@ModelAttribute 和 @InitBinder 用得很少,統一異常處理類其實也不必寫出這兩個引用註解的方法,直接保留@ExceptionHandler註解的方法便可學習
即把@ControllerAdvice註解內部使用@ExceptionHandler、@InitBinder、@ModelAttribute註解 的方法應用到全部的 @RequestMapping註解的方法。很是簡單,不過只有當使用@ExceptionHandler最有用,另外兩個用處不大。ui
該 @ControllerAdvice 註解很是簡單,能夠把異常處理器應用到全部控制器 @Controller ,而不是@Controller註解的單個控制器。 單個控制器請用 @ExceptionHandler 註解,這樣在該異常處理器對當前控制器的全部方法有效。.net
若是某控制器須要自定義處理異常,不用頂層的異常處理器,請在當前控制器內用 @ExceptionHandler 註解 ,這樣當前控制器的異常處理就在當前類
做用域:@ControllerAdvice > @ExceptionHandler > try catch
優先級: try catch > @ExceptionHandler > @ControllerAdvice
轉載參考:http://jinnianshilongnian.iteye.com/blog/1866350?utm_source=tuicool&utm_medium=referral
http://blog.csdn.net/ufo2910628/article/details/40399539