异常处理后,能够提供友好的用户界面,而不是一些错误的代码信息.
利用struts2的异常处理机制可以很方便的实现异常处理,你不再需要在Action中捕获异常,并抛出相关的异常了,这些都交给拦截器来帮你做了。在struts-default.xml中己经设置了拦截器,因此我们可以直接使用声明式异常.struts2-default-xml声明的拦截器如下:
- <interceptors>
- <interceptor name="exception"
- class="com.opensymphony.xwork.interceptor.ExceptionMappingInterceptor"/>
- </interceptors>
异常的类型可以分为两种:局部异常映射和全局异常映射
当Action抛出异常时,会在局部中和全局中查找与之相匹配的异常,如果局部和全局中都有满足的异常映射,以局部的为准.
可以使用Struts2的标签来输出异常信息
<s:property value="exception.message"/>
<s:property value="exceptionStack"/>
<global-results>
<result name="exceptionPage">/pages/fail.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="exceptionPage" exception="java.lang.Exception" />
</global-exception-mappings>
<interceptor-ref name="exception"></interceptor-ref>