天天看點

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

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 項目結構

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html
使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

3.2.2 Dao層代碼

Java代碼  

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

@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層代碼

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

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;

            throw new BusinessException("11", "service11");

            throw new BusinessException("21", "service21");

            throw new BusinessException("31", "service31");

            throw new BusinessException("41", "service41");

            throw new BusinessException("51", "service51");

            throw new ParameterException("Service Parameter Error");

    @Override

    public void dao(Integer id) throws Exception {

        testDao.exception(id);

3.2.4 Controller層代碼

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

@Controller

public class TestController {

    private TestService testService;

    @RequestMapping(value = "/controller.do", method = RequestMethod.GET)

    public void controller(HttpServletResponse response, Integer id) throws Exception {

            throw new BusinessException("10", "controller10");

            throw new BusinessException("20", "controller20");

            throw new BusinessException("30", "controller30");

            throw new BusinessException("40", "controller40");

            throw new BusinessException("50", "controller50");

            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頁面代碼

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

<%@ 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中增加以下内容:

Xml代碼  

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

<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,代碼如下:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

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中增加以下内容:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

<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注解聲明異常處理,代碼如下:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

public class BaseController {

    /** 基于@ExceptionHandler異常處理 */

    @ExceptionHandler

    public String exp(HttpServletRequest request, Exception ex) {

        request.setAttribute("ex", ex);

            return "error-business";

            return "error-parameter";

            return "error";

2、修改代碼,使所有需要異常處理的Controller都繼承該類,如下所示,修改後的TestController類繼承于BaseController:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

public class TestController extends BaseController

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檔案,增加以下内容:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

<!-- 出錯頁面定義 -->

<error-page>

    <exception-type>java.lang.Throwable</exception-type>

    <location>/500.jsp</location>

</error-page>

    <error-code>500</error-code>

    <error-code>404</error-code>

    <location>/404.jsp</location>

<!-- 這裡可繼續增加伺服器錯誤号的處理及對應顯示的頁面 -->

4 解決結果

1、運作測試項目顯示的首頁,如下圖所示:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

2、業務錯誤顯示的頁面,如下圖所示:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

3、參數錯誤顯示的頁面,如下圖所示:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

4、未知錯誤顯示的頁面,如下圖所示:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

5、伺服器内部錯誤頁面,如下圖所示:

使用SpringMVC統一異常處理實戰使用SpringMVC統一異常處理實戰http://www.bieryun.com/1177.html

5 總結

綜合上述可知,Spring MVC內建異常處理3種方式都可以達到統一異常處理的目标。從3種方式的優缺點比較,若隻需要簡單的內建異常處理,推薦使用SimpleMappingExceptionResolver即可;若需要內建的異常處理能夠更具個性化,提供給使用者更詳細的異常資訊,推薦自定義實作HandlerExceptionResolver接口的方式;若不喜歡Spring配置檔案或要實作“零配置”,且能接受對原有代碼的适當入侵,則建議使用@ExceptionHandler注解方式。

6 源代碼

源代碼項目如下所示,為Maven項目,若需運作,請自行擷取相關的依賴包。

點選這裡擷取源代碼

7 參考資料

[1] Spring MVC統一處理異常的方法

http://hi.baidu.com/99999999hao/blog/item/25da70174bfbf642f919b8c3.html

[2] SpringMVC 異常處理初探

http://exceptioneye.iteye.com/blog/1306150

[3] Spring3 MVC 深入研究

http://elf8848.iteye.com/blog/875830

[4] Spring MVC異常處理

http://blog.csdn.net/rj042/article/details/7380442