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

来源:互联网 发布:软件自学网视频教程 编辑:程序博客网 时间:2024/06/04 18:36

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

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

以上是全局异常的处理,也可以处理特定Action的异常,如下:

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

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

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

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

1<!--覆盖defultStack中的exception设置,启用它的日志功能-->
2<interceptor-ref name="exception">
3        <param name="exception.logEnabled">true</param
4        <param name="exception.logLevel">error</param>
5</interceptor-ref>
0 0
原创粉丝点击