開發interceptor的時候,了解action已經執行完畢而result還沒有開始執行的時間點往往很重要的。譬如在異常處理方面就是如此:在action處理的過程中,由于后臺的處理,出現的異常很可能是系統異常;而在result處理的過程中,異常則可能出現在為用戶呈現的頁面的時候,而不是由于系統問題。
下面給出了ExceptionInterceptor的代碼,該interceptor會在result開始執行之前與之后以不同的方式處理異常。在result開始執行之前,可以改變用于從action配置中查詢result的返回碼,而在webwork應用程序中,使用Action.ERROR是一個常用的實踐技巧:將Action.ERROR映射至向用戶提示錯誤的頁面。所以,需要捕獲異常并返回Action.ERROR。在result開始執行之后,來自interceptor的返回碼就不再那樣重要了,但是仍然可以獲得由beforeResult()方法回傳給result code,并且可以返回它。在以下離子中需要注意的一點是:由于interceptor必須是無狀態的,因此它為每一個ActionInvocation創建一個新的ExceptionHandler,可以保存該ActionInvocation的狀態。
ExceptionInterceptor:在result前后以不同的方式處理異常
/**
* @filename ExceptionInterceptor.java
* @author Rain_zhou
* @version ExceptionInterceptor,下午01:05:50
*/
package com.founder.study.forum.interceptor;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.Interceptor;
/**
* @author Rain_zhou
*
*/
public class ExceptionInterceptor implements Interceptor {
/* (non-Javadoc)
* @see com.opensymphony.xwork.interceptor.Interceptor#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.opensymphony.xwork.interceptor.Interceptor#init()
*/
public void init() {
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.opensymphony.xwork.interceptor.Interceptor#intercept(com.opensymphony.xwork.ActionInvocation)
*/
public String intercept(ActionInvocation arg0) throws Exception {
// TODO Auto-generated method stub
ExceptionHandler handler=new ExceptionHandler(arg0);
return handler.invoke();
}
}
/**
* @filename ExceptionHandler.java
* @author Rain_zhou
* @version ExceptionHandler,下午01:07:04
*/
package com.founder.study.forum.interceptor;
import com.founder.study.forum.helper.NoLimitException;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.PreResultListener;
/**
* @author Rain_zhou
*
*/
public class ExceptionHandler implements PreResultListener {
private ActionInvocation invocation;
private boolean beforeResult=true;
private String result=Action.ERROR;
public ExceptionHandler(ActionInvocation invocation){
this.invocation=invocation;
invocation.addPreResultListener(this);
}
String invoke(){
try{
result=invocation.invoke();
}catch(Exception e){
if(beforeResult){
return Action.ERROR;
}else{
return result;
}
}
return result;
}
/* (non-Javadoc)
* @see com.opensymphony.xwork.interceptor.PreResultListener#beforeResult(com.opensymphony.xwork.ActionInvocation, Java.lang.String)
*/
public void beforeResult(ActionInvocation arg0, String arg1) {
// TODO Auto-generated method stub
beforeResult=false;
result=arg1;
}
}