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>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!