原文:http://blog.csdn.net/ufo2910628/article/details/40399539
1 描述
在J2EE項目的開發中,不管是對底層的數據庫操作過程,還是業務層的處理過程,還是控制層的處理過程,都不可避免會遇到各種可預知的、不可預知的異常需要處理。每個過程都單獨處理異常,系統的代碼耦合度高,工作量大且不好統一,維護的工作量也很大。
那么,能不能將所有類型的異常處理從各處理過程解耦出來,這樣既保證了相關處理過程的功能較單一,也實現了異常信息的統一處理和維護?答案是肯定的。下面將介紹使用Spring MVC統一處理異常的解決和實現過程。
2 分析
Spring MVC處理異常有3種方式:
(1)使用Spring MVC提供的簡單異常處理器SimpleMappingExceptionResolver;
(2)實現Spring的異常處理接口HandlerExceptionResolver 自定義自己的異常處理器;
(3)使用@ExceptionHandler注解實現異常處理;
3 實戰
3.1 引言
為了驗證Spring MVC的3種異常處理方式的實際效果,我們需要開發一個測試項目,從Dao層、Service層、Controller層分別拋出不同的異常,然后分別集成3種方式進行異常處理,從而比較3種方式的優缺點。
3.2 實戰項目
3.2.1 項目結構
3.2.2 Dao層代碼
- @Repository("testDao")
- public class TestDao {
- public void exception(Integer id) throws Exception {
- switch(id) {
- case 1:
- throw new BusinessException("12", "dao12");
- case 2:
- throw new BusinessException("22", "dao22");
- case 3:
- throw new BusinessException("32", "dao32");
- case 4:
- throw new BusinessException("42", "dao42");
- case 5:
- throw new BusinessException("52", "dao52");
- default:
- throw new ParameterException("Dao Parameter Error");
- }
- }
- }
3.2.3 Service層代碼
- public interface TestService {
- public void exception(Integer id) throws Exception;
- public void dao(Integer id) throws Exception;
- }
- @Service("testService")
- public class TestServiceImpl implements TestService {
- @Resource
- private TestDao testDao;
- public void exception(Integer id) throws Exception {
- switch(id) {
- case 1:
- throw new BusinessException("11", "service11");
- case 2:
- throw new BusinessException("21", "service21");
- case 3:
- throw new BusinessException("31", "service31");
- case 4:
- throw new BusinessException("41", "service41");
- case 5:
- throw new BusinessException("51", "service51");
- default:
- throw new ParameterException("Service Parameter Error");
- }
- }
- @Override
- public void dao(Integer id) throws Exception {
- testDao.exception(id);
- }
- }
3.2.4 Controller層代碼
- @Controller
- public class TestController {
- @Resource
- private TestService testService;
- @RequestMapping(value = "/controller.do", method = RequestMethod.GET)
- public void controller(HttpServletResponse response, Integer id) throws Exception {
- switch(id) {
- case 1:
- throw new BusinessException("10", "controller10");
- case 2:
- throw new BusinessException("20", "controller20");
- case 3:
- throw new BusinessException("30", "controller30");
- case 4:
- throw new BusinessException("40", "controller40");
- case 5:
- throw new BusinessException("50", "controller50");
- default:
- throw new ParameterException("Controller Parameter Error");
- }
- }
- @RequestMapping(value = "/service.do", method = RequestMethod.GET)
- public void service(HttpServletResponse response, Integer id) throws Exception {
- testService.exception(id);
- }
- @RequestMapping(value = "/dao.do", method = RequestMethod.GET)
- public void dao(HttpServletResponse response, Integer id) throws Exception {
- testService.dao(id);
- }
- }
3.2.5 JSP頁面代碼
- <%@ page contentType="text/html; charset=UTF-8"%>
- <html>
- <head>
- <title>Maven Demo</title>
- </head>
- <body>
- <h1>所有的演示例子</h1>
- <h3>[url=./dao.do?id=1]Dao正常錯誤[/url]</h3>
- <h3>[url=./dao.do?id=10]Dao參數錯誤[/url]</h3>
- <h3>[url=./dao.do?id=]Dao未知錯誤[/url]</h3>
- <h3>[url=./service.do?id=1]Service正常錯誤[/url]</h3>
- <h3>[url=./service.do?id=10]Service參數錯誤[/url]</h3>
- <h3>[url=./service.do?id=]Service未知錯誤[/url]</h3>
- <h3>[url=./controller.do?id=1]Controller正常錯誤[/url]</h3>
- <h3>[url=./controller.do?id=10]Controller參數錯誤[/url]</h3>
- <h3>[url=./controller.do?id=]Controller未知錯誤[/url]</h3>
- <h3>[url=./404.do?id=1]404錯誤[/url]</h3>
- </body>
- </html>
3.3 集成異常處理
3.3.1 使用SimpleMappingExceptionResolver實現異常處理
1、在Spring的配置文件applicationContext.xml中增加以下內容:
- <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
- <!-- 定義默認的異常處理頁面,當該異常類型的注冊時使用 -->
- <property name="defaultErrorView" value="error"></property>
- <!-- 定義異常處理頁面用來獲取異常信息的變量名,默認名為exception -->
- <property name="exceptionAttribute" value="ex"></property>
- <!-- 定義需要特殊處理的異常,用類名或完全路徑名作為key,異常也頁名作為值 -->
- <property name="exceptionMappings">
- <props>
- <prop key="cn.basttg.core.exception.BusinessException">error-business</prop>
- <prop key="cn.basttg.core.exception.ParameterException">error-parameter</prop>
- <!-- 這里還可以繼續擴展對不同異常類型的處理 -->
- </props>
- </property>
- </bean>
2、啟動測試項目,經驗證,Dao層、Service層、Controller層拋出的異常(業務異常BusinessException、參數異常ParameterException和其它的異常Exception)都能准確顯示定義的異常處理頁面,達到了統一異常處理的目標。
3、從上面的集成過程可知,使用SimpleMappingExceptionResolver進行異常處理,具有集成簡單、有良好的擴展性、對已有代碼沒有入侵性等優點,但該方法僅能獲取到異常信息,若在出現異常時,對需要獲取除異常以外的數據的情況不適用。
3.3.2 實現HandlerExceptionResolver 接口自定義異常處理器
1、增加HandlerExceptionResolver 接口的實現類MyExceptionHandler,代碼如下:
- public class MyExceptionHandler implements HandlerExceptionResolver {
- public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
- Exception ex) {
- Map<String, Object> model = new HashMap<String, Object>();
- model.put("ex", ex);
- // 根據不同錯誤轉向不同頁面
- if(ex instanceof BusinessException) {
- return new ModelAndView("error-business", model);
- }else if(ex instanceof ParameterException) {
- return new ModelAndView("error-parameter", model);
- } else {
- return new ModelAndView("error", model);
- }
- }
- }
2、在Spring的配置文件applicationContext.xml中增加以下內容:
- <bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>
3、啟動測試項目,經驗證,Dao層、Service層、Controller層拋出的異常(業務異常BusinessException、參數異常ParameterException和其它的異常Exception)都能准確顯示定義的異常處理頁面,達到了統一異常處理的目標。
4、從上面的集成過程可知,使用實現HandlerExceptionResolver接口的異常處理器進行異常處理,具有集成簡單、有良好的擴展性、對已有代碼沒有入侵性等優點,同時,在異常處理時能獲取導致出現異常的對象,有利於提供更詳細的異常處理信息。
3.3.3 使用@ExceptionHandler注解實現異常處理
1、增加BaseController類,並在類中使用@ExceptionHandler注解聲明異常處理,代碼如下:
- public class BaseController {
- /** 基於@ExceptionHandler異常處理 */
- @ExceptionHandler
- public String exp(HttpServletRequest request, Exception ex) {
- request.setAttribute("ex", ex);
- // 根據不同錯誤轉向不同頁面
- if(ex instanceof BusinessException) {
- return "error-business";
- }else if(ex instanceof ParameterException) {
- return "error-parameter";
- } else {
- return "error";
- }
- }
- }
2、修改代碼,使所有需要異常處理的Controller都繼承該類,如下所示,修改后的TestController類繼承於BaseController:
- public class TestController extends BaseController
3、啟動測試項目,經驗證,Dao層、Service層、Controller層拋出的異常(業務異常BusinessException、參數異常ParameterException和其它的異常Exception)都能准確顯示定義的異常處理頁面,達到了統一異常處理的目標。
4、從上面的集成過程可知,使用@ExceptionHandler注解實現異常處理,具有集成簡單、有擴展性好(只需要將要異常處理的Controller類繼承於BaseController即可)、不需要附加Spring配置等優點,但該方法對已有代碼存在入侵性(需要修改已有代碼,使相關類繼承於BaseController),在異常處理時不能獲取除異常以外的數據。
3.4 未捕獲異常的處理
對於Unchecked Exception而言,由於代碼不強制捕獲,往往被忽略,如果運行期產生了Unchecked Exception,而代碼中又沒有進行相應的捕獲和處理,則我們可能不得不面對尷尬的404、500……等服務器內部錯誤提示頁面。
我們需要一個全面而有效的異常處理機制。目前大多數服務器也都支持在Web.xml中通過<error-page>(Websphere/Weblogic)或者<error-code>(Tomcat)節點配置特定異常情況的顯示頁面。修改web.xml文件,增加以下內容:
- <!-- 出錯頁面定義 -->
- <error-page>
- <exception-type>java.lang.Throwable</exception-type>
- <location>/500.jsp</location>
- </error-page>
- <error-page>
- <error-code>500</error-code>
- <location>/500.jsp</location>
- </error-page>
- <error-page>
- <error-code>404</error-code>
- <location>/404.jsp</location>
- </error-page>
- <!-- 這里可繼續增加服務器錯誤號的處理及對應顯示的頁面 -->
4 解決結果
1、運行測試項目顯示的首頁,如下圖所示:
2、業務錯誤顯示的頁面,如下圖所示:
3、參數錯誤顯示的頁面,如下圖所示:
4、未知錯誤顯示的頁面,如下圖所示:
5、服務器內部錯誤頁面,如下圖所示:
5 總結
綜合上述可知,Spring MVC集成異常處理3種方式都可以達到統一異常處理的目標。從3種方式的優缺點比較,若只需要簡單的集成異常處理,推薦使用SimpleMappingExceptionResolver即可;若需要集成的異常處理能夠更具個性化,提供給用戶更詳細的異常信息,推薦自定義實現HandlerExceptionResolver接口的方式;若不喜歡Spring配置文件或要實現“零配置”,且能接受對原有代碼的適當入侵,則建議使用@ExceptionHandler注解方式。