posts - 431,  comments - 344,  trackbacks - 0

开发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;
 }

}

posted on 2006-12-25 14:30 周锐 阅读(2048) 评论(0)  编辑  收藏 所属分类: Webwork

只有注册用户登录后才能发表评论。


网站导航: