struts2全局异常处理及配合log4j异常日志记录

在编写代码时除了使用try catch来捕获异常以外,还能够用struts2的声明式异常处理,即在Action中直接抛出异常交给struts2来处理,而且在xml文件中进行相应的配置,以下: java

<!--设置全局返回结果 -->
<global-results> 
       <result name="error">/webPage/exception/error.jsp</result>
       <result name="sql">/webPage/exception/sql_error.jsp</result>
</global-results>
<!--定义要捕获的异常-->
<global-exception-mappings>  
        <exception-mapping result="error" exception="java.lang.Exception"></exception-mapping> 
        <exception-mapping result="sql" exception="java.sql.SQLException"></exception-mapping> 
</global-exception-mappings>

以上是全局异常的处理,也能够处理特定Action的异常,以下: web

<action name="login" class="userAction" method="login">
        <exception-mapping result="login" exception="com.exceptions.LoginException"></exception-mapping>
        <result name="login">/webPage/exception/login_error.jsp</result>
</action>

特定Action的异常声明优先于全局异常。 sql

至于配合log4j记录异常日志是利用struts2中提供的异常拦截器ExceptionMappingInterceptor,当发生指定异常后,会由它处理,由于这个类有写日志的功能,默认是禁用的,所以直接将其启用便可,以下: app

<interceptor-ref name="defaultStack">
        <!--覆盖defultStack中的exception设置,启用它的日志功能-->
        <param name="exception.logEnabled">true</param> 
        <param name="exception.logLevel">error</param>
</interceptor-ref>
以上代码能够改为:

<!--覆盖defultStack中的exception设置,启用它的日志功能-->
<interceptor-ref name="exception">
       	<param name="exception.logEnabled">true</param> 
        <param name="exception.logLevel">error</param>
</interceptor-ref>
相关文章
相关标签/搜索