struts2提供了聲明式異常處理,可以針對(duì)不同的異常做不同的處理。我想攔截Action中的所有異常,然后通過Log4j進(jìn)行日志記錄,再呈現(xiàn)到頁面。
首先在struts配置文件中配上一個(gè)全局的ja
va.lang.Exception。這樣所有異常都會(huì)被這個(gè)exception-mapping所攔截,并返回一個(gè)name為ALL_EXCEPTION的result
<global-exception-mappings>
<exception-mapping result="ALL_EXCEPTION" exception="java.lang.Exception"/>
</global-exception-mappings>
再來配置一個(gè)<global-results>來處理異常,通過chain跳轉(zhuǎn)到exectionHandle這個(gè)action中
<global-results>
<result name="ALL_EXCEPTION" type="chain">exectionHandle</result>
</global-results>
exectionHandle配置,這里的action用spring來管理的(exectionHandleAction)。處理異常后返回到指定界面(界面用的veloctiy模板)。
<action name="exectionHandle" class="exectionHandleAction">
<result type="velocity">/WEB-INF/public_ucenter_shopmanage/ServerExceptionPage.html</result>
</action>
最后看一下action中的處理,直接用logo4j輸出。
public class ExceptionHandleAction extends ActionSupport{
private static final long serialVersionUID = 6019598646317953160L;
private static Logger logger = Logger.getLogger(ExceptionHandleAction.class);
@Override
public String execute() throws Exception {
String logoInfo = ActionContext.getContext().getValueStack().findString("exceptionStack");
logger.info(logoInfo);
logger.debug(logoInfo);
return SUCCESS;
}
}