在项目中采用了struts2的<global-results>&<global-exception-mappings>处理异常,并在web页面上显示异常,在这里备忘一下
1.在strtus.xml中配置如下
< result name = " unhandledException " >/ common / systemFail.jsp </ result >
< result name = " input " >/ common / headerMsg.jsp </ result >
</ global - results >
< global - exception - mappings >
< exception - mapping exception = " java.lang.Exception " result = " unhandledException " />
< exception - mapping exception = " com.xxxx.exception.GuiException " result = " input " />
</ global - exception - mappings >
GuiException是自定义的Exception
2.完成systemFail.jsp和headerMsg.jsp,headerMsg显示的是知道的Exception,systemFail.jsp显示unhandle的Exception
<% @ include file = " ../common/header.jsp " %>
< div style = " padding-top:30px " >
</ div >
< div id = " systemFailed " style = " text-align:left; padding-left:80px; padding-right:80px; " >
< s:property value = " exception " />
</ div >
< br />
< div style = " text-align:left; padding-left:80px; padding-right:80px; " >
< s:property value = " exceptionStack " />
</ div >
<% @ include file = " ../common/footer.jsp " %>
headerMsg.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<div id="errorMessage" class="errorMessageText">
<s:actionerror/>
<s:actionmessage/>
<s:if test="exception != null">
<s:if test="exception.errorCode != null">
<s:set name="errorCode" value="exception.errorCode"/>
<s:set name="args" value="exception.args"/>
<s:text name="${errorCode}">
<c:forEach var="arg" items="${args}">
<s:param>${arg}</s:param>
</c:forEach>
</s:text>
</s:if>
<s:else>
<s:property value="exception.message"/>
</s:else>
</s:if>
</div>
这里的Exception已经是自定义的GUIException(在struts.xml中配置过了),所以直接从里面取信息(args,errCode...)
3. 在Action中trhows GuiException,然后strtus2会默认使用exception的interceptor将Action中抛出的GUIException拦截,然后匹配xml文件,这样就完成了错误处理.
总结:
还是利用了struts2的interceptor机制,方便的拦截了异常.
<package name="pkg" extends="struts-default" abstract="true">
<global-results>
...
</global-results>
<global-exception-mappings>
...
</global-exception-mappings>
</package>
<package name="test" namespace="/test" extends="pkg">
</package>