1) 配置
使用Struts2时,在配置文件中配置异常映射就能拦截特定的异常,转入对应的页面。
<package name="exetionLearn" extends="struts-default" namespace="/exception">
<global-results>
<result name="showException">/WEB-INF/page/exceptionLearn/register.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="showException"exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
<action name="register_*"class="com.gathershell.action.exception.RegisterAction"method="{1}">
<result name="showException">/WEB-INF/page/exceptionLearn/register.jsp</result>
<result name="success">/WEB-INF/page/success.jsp</result>
<exception-mapping result="showException" exception="java.sql.SQLException"></exception-mapping>
</action>
</package>
上面的全局异常映射作用于整个pakage中所有Action,而在某个ation下配置的异常映射只作用本Action,并且它的优先级高,若它能匹配,就不再去用全局异常映射。
2) 页面
<s:property value="exception.message"/>
${exception.message }<br/>
${exceptionStack }
在页面上可用Struts2的标签或EL表达式输出异常信息。输出异常对象用exception.message,输出异常堆栈用exceptionStack。