Struts2的異常處理機制
Struts2采用聲明式的方法管理異常處理,因此我們無需在execute方法體內寫大量的try...catch...語句來捕獲異常,execute方法將產生的所有異常拋出,統一交由Struts2框架處理,我們只需在struts.xml文件中配置異常的映射機制,Struts2便能夠處理并轉入相應的視圖資源。
異常映射可分為全局異常映射和局部異常映射,它和<result .../>的性質是一樣的。
配置代碼如下:
Xml代碼
<struts>
<package name="struts2" extends="struts-default">
<!-- 配置全局異常映射 -->
<global-exception-mappings>
<exception-mapping result="sql" exception="java.sql.SQLException"/>
</global-exception-mappings>
<action name="login" class="com.test.action.LoginAction">
<!-- 配置局部異常映射 -->
<exception-mapping result="myException" exception="com.test.exception.MyException"/>
<result name="success">result.jsp</result>
<result name="sql">error.jsp</result>
<result name="myException">error.jsp</result>
</action>
</package>
</struts>
<struts>
<package name="struts2" extends="struts-default">
<!-- 配置全局異常映射 -->
<global-exception-mappings>
<exception-mapping result="sql" exception="java.sql.SQLException"/>
</global-exception-mappings>
<action name="login" class="com.test.action.LoginAction">
<!-- 配置局部異常映射 -->
<exception-mapping result="myException" exception="com.test.exception.MyException"/>
<result name="success">result.jsp</result>
<result name="sql">error.jsp</result>
<result name="myException">error.jsp</result>
</action>
</package>
</struts>
為了在異常處理頁面中顯示異常信息,我們可以使用<s:property/>標簽來輸出異常信息:
<s:property value="exception"/>:輸出異常信息本身
<s:property value="exceptionStack"/>:輸出異常堆棧信息