`
happyqing
  • 浏览: 3183509 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

转:使用Spring MVC统一异常处理实战

阅读更多
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层代码
Java代码 复制代码 收藏代码
  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. }  
@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层代码
Java代码 复制代码 收藏代码
  1. public interface TestService {   
  2.     public void exception(Integer id) throws Exception;   
  3.        
  4.     public void dao(Integer id) throws Exception;   
  5. }   
  6.   
  7. @Service("testService")   
  8. public class TestServiceImpl implements TestService {   
  9.     @Resource  
  10.     private TestDao testDao;   
  11.        
  12.     public void exception(Integer id) throws Exception {   
  13.         switch(id) {   
  14.         case 1:   
  15.             throw new BusinessException("11""service11");   
  16.         case 2:   
  17.             throw new BusinessException("21""service21");   
  18.         case 3:   
  19.             throw new BusinessException("31""service31");   
  20.         case 4:   
  21.             throw new BusinessException("41""service41");   
  22.         case 5:   
  23.             throw new BusinessException("51""service51");   
  24.         default:   
  25.             throw new ParameterException("Service Parameter Error");   
  26.         }   
  27.     }   
  28.   
  29.     @Override  
  30.     public void dao(Integer id) throws Exception {   
  31.         testDao.exception(id);   
  32.     }   
  33. }  
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层代码
Java代码 复制代码 收藏代码
  1. @Controller  
  2. public class TestController {   
  3.     @Resource  
  4.     private TestService testService;   
  5.        
  6.     @RequestMapping(value = "/controller.do", method = RequestMethod.GET)   
  7.     public void controller(HttpServletResponse response, Integer id) throws Exception {   
  8.         switch(id) {   
  9.         case 1:   
  10.             throw new BusinessException("10""controller10");   
  11.         case 2:   
  12.             throw new BusinessException("20""controller20");   
  13.         case 3:   
  14.             throw new BusinessException("30""controller30");   
  15.         case 4:   
  16.             throw new BusinessException("40""controller40");   
  17.         case 5:   
  18.             throw new BusinessException("50""controller50");   
  19.         default:   
  20.             throw new ParameterException("Controller Parameter Error");   
  21.         }   
  22.     }   
  23.        
  24.     @RequestMapping(value = "/service.do", method = RequestMethod.GET)   
  25.     public void service(HttpServletResponse response, Integer id) throws Exception {   
  26.         testService.exception(id);   
  27.     }   
  28.        
  29.     @RequestMapping(value = "/dao.do", method = RequestMethod.GET)   
  30.     public void dao(HttpServletResponse response, Integer id) throws Exception {   
  31.         testService.dao(id);   
  32.     }   
  33. }  
@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页面代码
Java代码 复制代码 收藏代码
  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.   
  12.   
  13. <h3>[url=./service.do?id=1]Service正常错误[/url]</h3>   
  14. <h3>[url=./service.do?id=10]Service参数错误[/url]</h3>   
  15. <h3>[url=./service.do?id=]Service未知错误[/url]</h3>   
  16.   
  17.   
  18. <h3>[url=./controller.do?id=1]Controller正常错误[/url]</h3>   
  19. <h3>[url=./controller.do?id=10]Controller参数错误[/url]</h3>   
  20. <h3>[url=./controller.do?id=]Controller未知错误[/url]</h3>   
  21.   
  22.   
  23. <h3>[url=./404.do?id=1]404错误[/url]</h3>   
  24. </body>   
  25. </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代码 复制代码 收藏代码
  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.             <!-- 这里还可以继续扩展对不同异常类型的处理 -->  
  13.         </props>  
  14.     </property>  
  15. </bean>  
	<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,代码如下:
Java代码 复制代码 收藏代码
  1. public class MyExceptionHandler implements HandlerExceptionResolver {   
  2.   
  3.     public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,   
  4.             Exception ex) {   
  5.         Map<String, Object> model = new HashMap<String, Object>();   
  6.         model.put("ex", ex);   
  7.            
  8.         // 根据不同错误转向不同页面   
  9.         if(ex instanceof BusinessException) {   
  10.             return new ModelAndView("error-business", model);   
  11.         }else if(ex instanceof ParameterException) {   
  12.             return new ModelAndView("error-parameter", model);   
  13.         } else {   
  14.             return new ModelAndView("error", model);   
  15.         }   
  16.     }   
  17. }  
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中增加以下内容:
Xml代码 复制代码 收藏代码
  1. <bean id="exceptionHandler" class="cn.basttg.core.exception.MyExceptionHandler"/>  
<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注解声明异常处理,代码如下:
Java代码 复制代码 收藏代码
  1. public class BaseController {   
  2.     /** 基于@ExceptionHandler异常处理 */  
  3.     @ExceptionHandler  
  4.     public String exp(HttpServletRequest request, Exception ex) {   
  5.            
  6.         request.setAttribute("ex", ex);   
  7.            
  8.         // 根据不同错误转向不同页面   
  9.         if(ex instanceof BusinessException) {   
  10.             return "error-business";   
  11.         }else if(ex instanceof ParameterException) {   
  12.             return "error-parameter";   
  13.         } else {   
  14.             return "error";   
  15.         }   
  16.     }   
  17. }  
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:
Java代码 复制代码 收藏代码
  1. public class TestController extends 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文件,增加以下内容:
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.   
  15. <!-- 这里可继续增加服务器错误号的处理及对应显示的页面 -->  
	<!-- 出错页面定义 -->
	<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注解方式。

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 MVC统一异常处理实战

    NULL 博文链接:https://cgs1999.iteye.com/blog/1547197

    看透spring mvc源代码分析与实践扫描版带目录+源码

    11. **异常处理**:Spring MVC提供了统一的异常处理机制,可以定义全局的异常处理器,将系统异常转化为友好的用户响应。 12. **RESTful支持**:Spring MVC支持创建RESTful风格的Web服务,通过@RequestMapping注解...

    Spring MVC+MYBatis企业应用实战

    《Spring MVC+MYBatis企业应用实战》这本书深入探讨了两个在Java企业级开发中广泛使用的框架——Spring MVC和MYBatis的集成应用。Spring MVC是Spring框架的一部分,专门用于构建Web应用程序,而MYBatis则是一个轻量...

    Spring-MVC-3.0.rar_Java spring mvc_spring mvc_spring ppt

    5. **HandlerExceptionResolvers**:异常处理器,用于统一处理Controller抛出的异常。 6. **Tiles view resolver集成**:支持Tiles视图技术,方便页面布局。 7. **New tags in JSP tags library**:提供了更多的JSP...

    springmvc 异常统一处理的三种方式详解.docx

    在Spring MVC框架中,异常处理是一项关键任务,它确保了应用程序在遇到错误或异常时能够以优雅的方式响应,提供统一的错误信息,并保持代码的整洁和模块化。本篇文章将详细探讨Spring MVC处理异常的三种主要方法:...

    spring mvc案例+配置+原理详解+架包

    4. **异常处理**:自定义异常处理器,统一处理应用中抛出的异常。 5. **数据验证**:使用Hibernate Validator或其他验证框架进行输入验证。 五、Spring MVC 实战案例 1. **Hello World**:创建第一个Spring MVC...

    Spring_MVC_3.0实战指南

    除此之外,Spring MVC还提供了统一异常处理机制,通过@ControllerAdvice和@ExceptionHandler注解,可以集中处理全局异常,提供友好的错误页面。另外,它还支持模板引擎,如FreeMarker和Thymeleaf,使开发者能用模板...

    基于注解配置和使用spring AOP(spring mvc框架)

    在SpringMVCTest项目中,你可以创建一个简单的Spring MVC应用程序,定义一些带有业务逻辑的服务方法,然后创建相应的切面来实现日志记录、异常处理或事务管理。通过运行和测试这些方法,你可以直观地看到AOP在实际...

    Spring MVC 配套资料

    6. 异常处理:可以自定义异常处理器,实现统一的错误页面。 7. AOP 集成:利用 Spring 的 AOP 支持实现切面编程。 五、学习资源 "SpringMvc 学习笔记" 可能包含了关于这些概念的详细解释和实例,帮助读者深入理解 ...

    Spring3.0MvcDemo

    《Spring 3.0 MVC 框架深度解析与实战指南》 在现代Web开发中,Spring框架以其强大的功能和灵活性备受青睐,尤其是其MVC模块,为构建高性能、易于维护的Web应用提供了坚实的基础。本文将深入探讨Spring 3.0版本的...

    spring-mvc-showcase

    Spring MVC提供了全局和局部的异常处理器,如@ControllerAdvice和@ExceptionHandler,可以统一处理程序中的异常。同时,通过消息源(MessageSource)实现国际化,使应用能够根据用户选择的语言显示不同的文本。 八...

    spring mvc的相关教程

    Spring MVC提供了统一的异常处理机制,可以自定义异常处理器,当业务逻辑中抛出异常时,会按照预设的规则进行处理。 七、RESTful API开发 Spring MVC非常适合构建RESTful服务,通过@RequestMapping注解配合HTTP动词...

    【Java实战教程】11. 整合 Spring 与 Spring Mvc框架.haozip02.zip

    - 使用Spring MVC的异常处理机制,如@ControllerAdvice和@ExceptionHandler,来统一处理全局异常。 - 配置视图解析器,如InternalResourceViewResolver,指定视图路径前缀和后缀,以便Spring MVC能正确找到JSP或...

    Spring Mvc Demo

    5. **更好的异常处理**:Spring MVC的异常处理机制允许开发者创建全局的异常处理器,使得错误处理更规范统一。 在"SpringMvc02"这个项目中,你可以看到如何设置Spring MVC的环境,包括`web.xml`配置、`spring-mvc-...

    Spring MVC中文翻译文档

    4. **异常处理**:可以全局或局部地定义异常处理器,统一处理异常。 5. **国际化**:支持多语言环境,通过LocaleResolver和MessageSource实现。 6. **RESTful支持**:通过HTTP动词(GET、POST、PUT、DELETE等)...

    86丨开源实战四(下):总结Spring框架用到的11种设计模式1

    Spring MVC中的HandlerExceptionResolver接口及其实现类,构建了一个异常处理的职责链,一个请求会沿着这个链传递,直到找到合适的处理器处理异常。 11. **建造者模式(Builder Pattern)**: 在Spring Boot的配置...

    me(spring)

    8. **异常处理**:Spring MVC 提供了一套统一的异常处理机制,允许开发者自定义全局异常处理器,提高错误处理的规范性和用户体验。 9. **国际化支持(i18n)**:Spring MVC 提供了强大的国际化支持,可以通过配置...

    【预习资料】一步一步手绘Spring MVC运行时序图.pdf

    6. HandlerExceptionResolvers:处理控制器抛出的异常,提供统一的异常处理机制。 7. RequestToViewNameTranslator:根据请求信息推断视图名称。 8. ViewResolvers:查找并解析视图,支持多种视图技术,如JSP、...

Global site tag (gtag.js) - Google Analytics