詳解使用Spring MVC統(tǒng)一異常處理實戰(zhàn)
1 描述
在J2EE項目的開發(fā)中,不管是對底層的數(shù)據(jù)庫操作過程,還是業(yè)務(wù)層的處理過程,還是控制層的處理過程,都不可避免會遇到各種可預(yù)知的、不可預(yù)知的異常需要處理。每個過程都單獨處理異常,系統(tǒng)的代碼耦合度高,工作量大且不好統(tǒng)一,維護的工作量也很大。
那么,能不能將所有類型的異常處理從各處理過程解耦出來,這樣既保證了相關(guān)處理過程的功能較單一,也實現(xiàn)了異常信息的統(tǒng)一處理和維護?答案是肯定的。下面將介紹使用Spring MVC統(tǒng)一處理異常的解決和實現(xiàn)過程。
2 分析
Spring MVC處理異常有3種方式:
(1)使用Spring MVC提供的簡單異常處理器SimpleMappingExceptionResolver;
(2)實現(xiàn)Spring的異常處理接口HandlerExceptionResolver 自定義自己的異常處理器;
(3)使用@ExceptionHandler注解實現(xiàn)異常處理;
3 實戰(zhàn)
3.1 引言
為了驗證Spring MVC的3種異常處理方式的實際效果,我們需要開發(fā)一個測試項目,從Dao層、Service層、Controller層分別拋出不同的異常,然后分別集成3種方式進行異常處理,從而比較3種方式的優(yōu)缺點。
3.2 實戰(zhàn)項目
3.2.1 項目結(jié)構(gòu)

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參數(shù)錯誤[/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參數(shù)錯誤[/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參數(shù)錯誤[/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實現(xiàn)異常處理
1、在Spring的配置文件applicationContext.xml中增加以下內(nèi)容:
<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>
<!-- 這里還可以繼續(xù)擴展對不同異常類型的處理 -->
</props>
</property>
</bean>
2、啟動測試項目,經(jīng)驗證,Dao層、Service層、Controller層拋出的異常(業(yè)務(wù)異常BusinessException、參數(shù)異常ParameterException和其它的異常Exception)都能準確顯示定義的異常處理頁面,達到了統(tǒng)一異常處理的目標。
3、從上面的集成過程可知,使用SimpleMappingExceptionResolver進行異常處理,具有集成簡單、有良好的擴展性、對已有代碼沒有入侵性等優(yōu)點,但該方法僅能獲取到異常信息,若在出現(xiàn)異常時,對需要獲取除異常以外的數(shù)據(jù)的情況不適用。
3.3.2 實現(xiàn)HandlerExceptionResolver 接口自定義異常處理器
1、增加HandlerExceptionResolver 接口的實現(xiàn)類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);
// 根據(jù)不同錯誤轉(zhuǎn)向不同頁面
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中增加以下內(nèi)容:
<bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>
3、啟動測試項目,經(jīng)驗證,Dao層、Service層、Controller層拋出的異常(業(yè)務(wù)異常BusinessException、參數(shù)異常ParameterException和其它的異常Exception)都能準確顯示定義的異常處理頁面,達到了統(tǒng)一異常處理的目標。
4、從上面的集成過程可知,使用實現(xiàn)HandlerExceptionResolver接口的異常處理器進行異常處理,具有集成簡單、有良好的擴展性、對已有代碼沒有入侵性等優(yōu)點,同時,在異常處理時能獲取導(dǎo)致出現(xiàn)異常的對象,有利于提供更詳細的異常處理信息。
3.3.3 使用@ExceptionHandler注解實現(xiàn)異常處理
1、增加BaseController類,并在類中使用@ExceptionHandler注解聲明異常處理,代碼如下:
public class BaseController {
/** 基于@ExceptionHandler異常處理 */
@ExceptionHandler
public String exp(HttpServletRequest request, Exception ex) {
request.setAttribute("ex", ex);
// 根據(jù)不同錯誤轉(zhuǎn)向不同頁面
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、啟動測試項目,經(jīng)驗證,Dao層、Service層、Controller層拋出的異常(業(yè)務(wù)異常BusinessException、參數(shù)異常ParameterException和其它的異常Exception)都能準確顯示定義的異常處理頁面,達到了統(tǒng)一異常處理的目標。
4、從上面的集成過程可知,使用@ExceptionHandler注解實現(xiàn)異常處理,具有集成簡單、有擴展性好(只需要將要異常處理的Controller類繼承于BaseController即可)、不需要附加Spring配置等優(yōu)點,但該方法對已有代碼存在入侵性(需要修改已有代碼,使相關(guān)類繼承于BaseController),在異常處理時不能獲取除異常以外的數(shù)據(jù)。
3.4 未捕獲異常的處理
對于Unchecked Exception而言,由于代碼不強制捕獲,往往被忽略,如果運行期產(chǎn)生了Unchecked Exception,而代碼中又沒有進行相應(yīng)的捕獲和處理,則我們可能不得不面對尷尬的404、500……等服務(wù)器內(nèi)部錯誤提示頁面。
我們需要一個全面而有效的異常處理機制。目前大多數(shù)服務(wù)器也都支持在Web.xml中通過<error-page>(Websphere/Weblogic)或者<error-code>(Tomcat)節(jié)點配置特定異常情況的顯示頁面。修改web.xml文件,增加以下內(nèi)容:
<!-- 出錯頁面定義 --> <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> <!-- 這里可繼續(xù)增加服務(wù)器錯誤號的處理及對應(yīng)顯示的頁面 -->
4 解決結(jié)果
1、運行測試項目顯示的首頁,如下圖所示:

2、業(yè)務(wù)錯誤顯示的頁面,如下圖所示:

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

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

5、服務(wù)器內(nèi)部錯誤頁面,如下圖所示:

5 總結(jié)
綜合上述可知,Spring MVC集成異常處理3種方式都可以達到統(tǒng)一異常處理的目標。從3種方式的優(yōu)缺點比較,若只需要簡單的集成異常處理,推薦使用SimpleMappingExceptionResolver即可;若需要集成的異常處理能夠更具個性化,提供給用戶更詳細的異常信息,推薦自定義實現(xiàn)HandlerExceptionResolver接口的方式;若不喜歡Spring配置文件或要實現(xiàn)“零配置”,且能接受對原有代碼的適當入侵,則建議使用@ExceptionHandler注解方式。
6 源代碼
源代碼項目如下所示,為Maven項目,若需運行,請自行獲取相關(guān)的依賴包。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決Mybatis的serverTimezone時區(qū)出現(xiàn)問題
這篇文章主要介紹了解決Mybatis的serverTimezone時區(qū)出現(xiàn)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
在IDEA中創(chuàng)建父工程和子模塊module的方法步驟
這篇文章主要介紹了在IDEA中創(chuàng)建父工程和子模塊module的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-02-02
淺談升級Spring Cloud到Finchley后的一點坑
這篇文章主要介紹了淺談升級Spring Cloud到Finchley后的一點坑,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
spring-boot整合ehcache實現(xiàn)緩存機制的方法
spring-boot是一個快速的集成框架,其設(shè)計目的是用來簡化新Spring應(yīng)用的初始搭建以及開發(fā)過程。這篇文章主要介紹了spring-boot整合ehcache實現(xiàn)緩存機制,需要的朋友可以參考下2018-01-01
Java?Web中ServletContext對象詳解與應(yīng)用
ServletContext是一個容器,可以用來存放變量,供一個web項目中多個Servlet共享,下面這篇文章主要給大家介紹了關(guān)于Java?Web中ServletContext對象詳解與應(yīng)用的相關(guān)資料,需要的朋友可以參考下2023-04-04

