使用Spring实现异常统一处理【一】

本文介绍了一种在Spring MVC中实现异常处理的方法,通过自定义SimpleMappingExceptionResolver来支持JSP和JSON异常处理,并提供了详细的配置步骤。

最近在搭建新的应用框架,彻底抛弃了struts,应用spring mvc,在jsp端也只使用jstl和jquery,根据情况可能会用tile。

异常的统一处理,是框架必要考虑点。

Spring提供两种方式实现异常处理:一种是直接实现自己的HandlerExceptionResolver,另一种是使用注解的方式实现一个专门用于处理异常的Controller——ExceptionHandler。

由于方法二需要对每个Controller类的提供一个异常方法,所以不采用该方法。

        一、直接实现自己的HandlerExceptionResolver

            HandlerExceptionResolver是一个接口,Spring提供其两个实现:DefaultExceptionResolver和SimpleMappingExceptionResolver,

         DefaultExceptionResolver配置性不强,所以决定自定义一个SimpleMappingExceptionResolver继承Spring的SimpleMappingExceptionResolver,在其基础上同时支持jsp和json的异常捕捉。

         1、自定义SimpleMappingExceptionResolver类

public class CustomSimpleMappingExceptionResolver extends
		SimpleMappingExceptionResolver {

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String viewName = super.determineViewName(ex, request);  
        if (viewName != null) {// JSP格式返回  
            if (!(request.getHeader("accept").indexOf("application/json") > -1 || (request  
                    .getHeader("X-Requested-With")!= null && request  
                    .getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1))) {  
                // 如果不是异步请求  
                // Apply HTTP status code for error views, if specified.  
                // Only apply it if we're processing a top-level request.  
                Integer statusCode = super.determineStatusCode(request, viewName);  
                if (statusCode != null) {  
                    super.applyStatusCodeIfPossible(request, response, statusCode);  
                }  
                return super.getModelAndView(viewName, ex, request);  
            } else {// JSON格式返回  
                try {  
                    PrintWriter writer = response.getWriter();  
                    writer.write(ex.getMessage());  
                    writer.flush();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                return null;  
  
            }  
        } else {  
            return null;  
        }  //if
	}//doResolveException

}
    

2、修改Spring的配置XML,定义CustomSimpleMappingExceptionResolver的Bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


    <!-- 配置WebBindingInitializer ,比如日期初始化等 -->
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="mappingJacksonHttpMessageConverter" />
</util:list>
</property>
</bean>

<!-- Autodetect annotated controllers -->
<context:component-scan
base-package="com.winssage.ccp.module.*,com.winssage.ccp.module.*.*," />

<!--mvc:annotation-driven 会自动注册DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个实例 -->
<!-- 启动SpringMVC的注解功能,它会自动注册HandlerMapping、 HandlerAdapter、ExceptionResolver的相关实例 -->
<mvc:annotation-driven />




<!-- JSON转换器 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>


 <!-- 异常处理-->   
 <bean id="exceptionResolver" class="com.winssage.framework.server.exception.CustomSimpleMappingExceptionResolver">  
    <property name="defaultErrorView" value="error/errorpage"/>  
    <!-- 定义异常处理页面用来获取异常信息的变量名,如果不添加exceptionAttribute属性,则默认为exception -->  
    <property name="exceptionAttribute" value="exception"/>  
      <property name="exceptionMappings">   
        <props>   
          <prop key="java.lang.exception">error/errorpage</prop>  <!-- 不设置将根据defaultErrorView -->         
       </props>   
     </property>   
    </bean> 
    
    
<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
in the /WEB-INF/views directory -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/" />
<property name="suffix" value=".jsp" />
</bean>


</beans>
             3、创建errorpage.jsp,放置相应目录

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!error!~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ${exception} </h1>
    </body>
</html>

        4、如上所配置,当jsp加载遇到异常,则跳转到errorpage.jsp;如通过json访问服务器发生异常,则在error方法中直接返回错误信息,如下例,在error方法的data.responseText直接显示错误信息。

function ajaxTest()  
    {  
        $.ajax( {  
            type : 'GET',  
            //contentType : 'application/json',     
            url : '${basePath}/josontest.html',     
            async: false,//禁止ajax的异步操作,使之顺序执行。  
            dataType : 'json',  
            success : function(data,textStatus){  
                alert(JSON.stringify(data));  
            },  
            error : function(data,textstatus){  
                alert(data.responseText);  
            }  
        });  
    }  



二、参考

1、http://m.blog.youkuaiyun.com/blog/mr__fang/9092511
2、http://blog.youkuaiyun.com/sinlff/article/details/5872724






【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring Boot,Spring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程步步做下来,之后再去进步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring Boot、Spring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值