http://cgs1999.iteye.com/blog/1547197

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层代码

  1. @Repository("testDao")
  2. public class TestDao {
  3. public void exception(Integer id) throws Exception {
  4. switch(id) {
  5. case 1:
  6. throw new BusinessException("12", "dao12");
  7. case 2:
  8. throw new BusinessException("22", "dao22");
  9. case 3:
  10. throw new BusinessException("32", "dao32");
  11. case 4:
  12. throw new BusinessException("42", "dao42");
  13. case 5:
  14. throw new BusinessException("52", "dao52");
  15. default:
  16. throw new ParameterException("Dao Parameter Error");
  17. }
  18. }
  19. }

3.2.3 Service层代码

  1. public interface TestService {
  2. public void exception(Integer id) throws Exception;
  3. public void dao(Integer id) throws Exception;
  4. }
  5. @Service("testService")
  6. public class TestServiceImpl implements TestService {
  7. @Resource
  8. private TestDao testDao;
  9. public void exception(Integer id) throws Exception {
  10. switch(id) {
  11. case 1:
  12. throw new BusinessException("11", "service11");
  13. case 2:
  14. throw new BusinessException("21", "service21");
  15. case 3:
  16. throw new BusinessException("31", "service31");
  17. case 4:
  18. throw new BusinessException("41", "service41");
  19. case 5:
  20. throw new BusinessException("51", "service51");
  21. default:
  22. throw new ParameterException("Service Parameter Error");
  23. }
  24. }
  25. @Override
  26. public void dao(Integer id) throws Exception {
  27. testDao.exception(id);
  28. }
  29. }

3.2.4 Controller层代码

  1. @Controller
  2. public class TestController {
  3. @Resource
  4. private TestService testService;
  5. @RequestMapping(value = "/controller.do", method = RequestMethod.GET)
  6. public void controller(HttpServletResponse response, Integer id) throws Exception {
  7. switch(id) {
  8. case 1:
  9. throw new BusinessException("10", "controller10");
  10. case 2:
  11. throw new BusinessException("20", "controller20");
  12. case 3:
  13. throw new BusinessException("30", "controller30");
  14. case 4:
  15. throw new BusinessException("40", "controller40");
  16. case 5:
  17. throw new BusinessException("50", "controller50");
  18. default:
  19. throw new ParameterException("Controller Parameter Error");
  20. }
  21. }
  22. @RequestMapping(value = "/service.do", method = RequestMethod.GET)
  23. public void service(HttpServletResponse response, Integer id) throws Exception {
  24. testService.exception(id);
  25. }
  26. @RequestMapping(value = "/dao.do", method = RequestMethod.GET)
  27. public void dao(HttpServletResponse response, Integer id) throws Exception {
  28. testService.dao(id);
  29. }
  30. }

3.2.5 JSP页面代码

  1. <%@ page contentType="text/html; charset=UTF-8"%>
  2. <html>
  3. <head>
  4. <title>Maven Demo</title>
  5. </head>
  6. <body>
  7. <h1>所有的演示例子</h1>
  8. <h3>[url=./dao.do?id=1]Dao正常错误[/url]</h3>
  9. <h3>[url=./dao.do?id=10]Dao参数错误[/url]</h3>
  10. <h3>[url=./dao.do?id=]Dao未知错误[/url]</h3>
  11. <h3>[url=./service.do?id=1]Service正常错误[/url]</h3>
  12. <h3>[url=./service.do?id=10]Service参数错误[/url]</h3>
  13. <h3>[url=./service.do?id=]Service未知错误[/url]</h3>
  14. <h3>[url=./controller.do?id=1]Controller正常错误[/url]</h3>
  15. <h3>[url=./controller.do?id=10]Controller参数错误[/url]</h3>
  16. <h3>[url=./controller.do?id=]Controller未知错误[/url]</h3>
  17. <h3>[url=./404.do?id=1]404错误[/url]</h3>
  18. </body>
  19. </html>

3.3 集成异常处理 
3.3.1 使用SimpleMappingExceptionResolver实现异常处理 
1、在Spring的配置文件applicationContext.xml中增加以下内容:

  1. <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
  2. <!-- 定义默认的异常处理页面,当该异常类型的注册时使用 -->
  3. <property name="defaultErrorView" value="error"></property>
  4. <!-- 定义异常处理页面用来获取异常信息的变量名,默认名为exception -->
  5. <property name="exceptionAttribute" value="ex"></property>
  6. <!-- 定义需要特殊处理的异常,用类名或完全路径名作为key,异常也页名作为值 -->
  7. <property name="exceptionMappings">
  8. <props>
  9. <prop key="cn.basttg.core.exception.BusinessException">error-business</prop>
  10. <prop key="cn.basttg.core.exception.ParameterException">error-parameter</prop>
  11. <!-- 这里还可以继续扩展对不同异常类型的处理 -->
  12. </props>
  13. </property>
  14. </bean>

2、启动测试项目,经验证,Dao层、Service层、Controller层抛出的异常(业务异常BusinessException、参数异常ParameterException和其它的异常Exception)都能准确显示定义的异常处理页面,达到了统一异常处理的目标。

3、从上面的集成过程可知,使用SimpleMappingExceptionResolver进行异常处理,具有集成简单、有良好的扩展性、对已有代码没有入侵性等优点,但该方法仅能获取到异常信息,若在出现异常时,对需要获取除异常以外的数据的情况不适用。

3.3.2 实现HandlerExceptionResolver 接口自定义异常处理器 
1、增加HandlerExceptionResolver 接口的实现类MyExceptionHandler,代码如下:

  1. public class MyExceptionHandler implements HandlerExceptionResolver {
  2. public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
  3. Exception ex) {
  4. Map<String, Object> model = new HashMap<String, Object>();
  5. model.put("ex", ex);
  6. // 根据不同错误转向不同页面
  7. if(ex instanceof BusinessException) {
  8. return new ModelAndView("error-business", model);
  9. }else if(ex instanceof ParameterException) {
  10. return new ModelAndView("error-parameter", model);
  11. } else {
  12. return new ModelAndView("error", model);
  13. }
  14. }
  15. }

2、在Spring的配置文件applicationContext.xml中增加以下内容:

  1. <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注解声明异常处理,代码如下:

  1. public class BaseController {
  2. /** 基于@ExceptionHandler异常处理 */
  3. @ExceptionHandler
  4. public String exp(HttpServletRequest request, Exception ex) {
  5. request.setAttribute("ex", ex);
  6. // 根据不同错误转向不同页面
  7. if(ex instanceof BusinessException) {
  8. return "error-business";
  9. }else if(ex instanceof ParameterException) {
  10. return "error-parameter";
  11. } else {
  12. return "error";
  13. }
  14. }
  15. }

2、修改代码,使所有需要异常处理的Controller都继承该类,如下所示,修改后的TestController类继承于BaseController:

  1. 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文件,增加以下内容:

  1. <!-- 出错页面定义 -->
  2. <error-page>
  3. <exception-type>java.lang.Throwable</exception-type>
  4. <location>/500.jsp</location>
  5. </error-page>
  6. <error-page>
  7. <error-code>500</error-code>
  8. <location>/500.jsp</location>
  9. </error-page>
  10. <error-page>
  11. <error-code>404</error-code>
  12. <location>/404.jsp</location>
  13. </error-page>
  14. <!-- 这里可继续增加服务器错误号的处理及对应显示的页面 -->

4 解决结果 
1、运行测试项目显示的首页,如下图所示: 

2、业务错误显示的页面,如下图所示: 

3、参数错误显示的页面,如下图所示: 

4、未知错误显示的页面,如下图所示: 

5、服务器内部错误页面,如下图所示: 

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

spring异常处理的更多相关文章

  1. Spring异常处理@ExceptionHandler

    最近学习Spring时,认识到Spring异常处理的强大.之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑: try{ ... ...

  2. Unit06: Spring对JDBC的 整合支持 、 Spring+JDBC Template、Spring异常处理

    Unit06: Spring对JDBC的 整合支持 . Spring+JDBC Template .Spring异常处理 1. springmvc提供的异常处理机制 我们可以将异常抛给spring框架 ...

  3. Spring 异常处理三种方式 @ExceptionHandler

    异常处理方式一. @ExceptionHandler 异常处理方式二. 实现HandlerExceptionResolver接口 异常处理方式三. @ControllerAdvice+@Excepti ...

  4. spring 异常处理的方式?

    一.使用SimpleMappingExceptionResolver解析器 1.1在mvc中进行 配置. <?xml version="1.0" encoding=" ...

  5. Spring --- 异常处理机制

    1.定义全局异常处理器,为全局的异常,如出现将调用 error.JSP <!-- 定义异常处理器 --> <bean class="org.springframework. ...

  6. spring 异常处理

    1. 实现接口 HandlerExceptionResolver 捕获异常 2.@ExceptionHandler 在方法添加注解,捕获本地controller异常 3.@ControllerAdvi ...

  7. Spring MVC基础知识整理➣国际化和异常处理

    概述 Spring框架为WEB项目提供了国际化以及异常处理机制.所谓的国际化也就是不同国籍,显示不同国籍的语言与符号.异常处理,也就是能够捕获WEB项目下的所有异常信息,并能处理记录这些异常信息机制. ...

  8. Spring全局异常处理

    最近学习Spring时,认识到Spring异常处理的强大.之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑: 1 try{ 2 ...

  9. spring boot 初试,springboot入门,springboot helloworld例子

    因为项目中使用了spring boot ,之前没接触过,所以写个helloworld玩玩看,当做springboot的一个入门例子.搜索 spring boot.得到官方地址:http://proje ...

随机推荐

  1. C# 经典入门12章-使用泛型类型-2

  2. zf-关于分页的行数如何配置

    公司的项目分页显示行数是在web.xml里配置的 对应的java 文件是 BaseAction 这个文件里面写的就是分页的代码

  3. 归心似箭,IT达人分享抢票攻略

    [51CTO专稿]随着春节一天天临近,“购票难”的问题也愈发凸显,猎豹.火狐.360等“春运抢票神器”占领了各大网站的重要版面,“技术抢票”成为炙手可热的话题,看看身为程序员的邓以克是如何抢到回家的票 ...

  4. Ubuntu 下开发 Android 环境变量设置

    -----------------------------------------------------ANDROID_SDK_HOME:/home/cmm/avds PATH:/home/cmm/ ...

  5. tinkphp5.0 traits 的引入

    Traits引入 ThinkPHP 5.0开始采用trait功能(PHP5.4+)来作为一种扩展机制,可以方便的实现一个类库的多继承问题. trait是一种为类似 PHP 的单继承语言而准备的代码复用 ...

  6. 在js中如何得到上传文件的大小。

    <html>  <head>  <script language="javascript">    function getSize() {   ...

  7. 采用多线程方式,解决由于查询等待造成winfrom假死问题

    1.这里是触发一个比较耗时的操作,比如一次大数据量的查询: Thread thread = new Thread(new ThreadStart(DoWord)); thread.Start(); 2 ...

  8. 从客户端检测到有潜在危险的 Reque

    web.config里面加上<httpRuntime requestValidationMode="2.0" />如下<system.web><htt ...

  9. iOS navigationBar 的isTranslucent属性

    苹果文档: A Boolean value indicating whether the navigation bar is translucent (YES) or not (NO). The de ...

  10. iOS平台软件开发工具(一)-新建的工程使用CocoaPods工具集成第三方框架

    CocoaPods是一款集合了上千个第三方开源库的开发工具,能够大幅度的提升团队项目的开发效率,降低时间成本. 那么就看一下CocoaPods这个工具在项目中的使用体现吧. 我们马上用ASIHTTPR ...