读书人

struts2默许拦截器之exception

发布时间: 2012-07-08 17:43:43 作者: rapoo

struts2默认拦截器之exception

?

在struts2的struts-default.xml中定义了一个name为exception拦截器,实现类是com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor,它的作用是对action中的异常进行处理(输出异常日志,与配置文件中的<exception-mapping/>匹配).?

该拦截器有三个参数,分别是:

a、logEnabled (可选) -是否将异常信息打印到日志中,默认为false?

b、logLevel (可选) - 打印异常的日志级别,可选(trace, debug, info, warn, error, fatal),默认是debug

c、logCategory (可选) - 指定logger的种类,默认使用"com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"

?

首先说明一下 struts.xml 中的<exception-mapping/>配置。

<exception-mapping/> 是将异常类型与result进行对应,该元素需要指定两个属性:1,exception:此属性指定该异常映射所设置的异常类型。 2,result:此属性指定Action出现该异常时,系统转入result属性所指向的结果。 而 <exception-mapping/>也分为两种:1,局部异常映射:exception-mapping/元素作为action/元素的子元素配置。2,全局异常映射:exception-mapping/元素作为global-exception-mappings/>元素的子元素配置。

例如:?

?

?使用Struts2的标签来输出异常信息:

?

<s:property value="exception"/>:输出异常对象本身。

<s:property value="exceptionStack"/>: 输出异常堆栈信息。

由于exception拦截器已经在默认拦截器栈defaultStack中,所以无需进行配置。

接下来我们看一下exception拦截器都做了什么事情:

?

?

?

    protected String findResultFromExceptions(List<ExceptionMappingConfig> exceptionMappings, Throwable t) {        String result = null;        //寻找exceptionMappings中与异常最匹配的result        if (exceptionMappings != null) {            int deepest = Integer.MAX_VALUE;            for (Object exceptionMapping : exceptionMappings) {                ExceptionMappingConfig exceptionMappingConfig = (ExceptionMappingConfig) exceptionMapping;                int depth = getDepth(exceptionMappingConfig.getExceptionClassName(), t);                if (depth >= 0 && depth < deepest) {                    deepest = depth;                    result = exceptionMappingConfig.getResult();                }            }        }        return result;    }    /**     * Return the depth to the superclass matching. 0 means ex matches exactly. Returns -1 if there's no match.     * Otherwise, returns depth. Lowest depth wins.     *     * @param exceptionMapping  the mapping classname     * @param t  the cause     * @return the depth, if not found -1 is returned.     */    public int getDepth(String exceptionMapping, Throwable t) {        return getDepth(exceptionMapping, t.getClass(), 0);    }    private int getDepth(String exceptionMapping, Class exceptionClass, int depth) {        if (exceptionClass.getName().contains(exceptionMapping)) {            // Found it!            return depth;        }        // If we've gone as far as we can go and haven't found it...        if (exceptionClass.equals(Throwable.class)) {            return -1;        }        return getDepth(exceptionMapping, exceptionClass.getSuperclass(), depth + 1);    }

?handleLogging方法打印日志,findResultFromExceptions方法从配置中寻找与异常最匹配的result返回。

?

?

?

版权所有,转载请标明出处:http://blogwarning.iteye.com/blog/1334947

读书人网 >软件架构设计

热点推荐