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

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

<!--设置全局返回结果 -->
<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的异常,如下:

<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的异常声明优先于全局异常。

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

<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>



你可能感兴趣的:(异常处理,log4j,struts2,日志记录)