技术开发 频道

WebWork2.2学习笔记之Interceptor


IT168技术文档】 
    WebWork的核心是Xwork,而Xwork的核心可能就是Interceptor了。上周我在学习Action的时候已经接触到了Interceptor的概念,Interceptor的作用就是在执行Action前后进行拦截,使用户有机会执行其他操作。 

    在Xwork中,AOP是通过Action、ActionInvocation和Interceptor这三个接口完成的。WebWork通过Action代理类ActionProxy来执行Action的execute方法,而该方法则调用ActionInvocation的invokeAction方法具体执行Action中的方法。在DefaultActionInvocation的invoke方法中可以看到拦截器的执行逻辑,代码如下:
public String invoke() throws Exception { ...... if (interceptors.hasNext()) { InterceptorMapping interceptor = (InterceptorMapping) interceptors.next(); resultCode = interceptor.getInterceptor().intercept(this); } else { resultCode = invokeActionOnly(); } ...... }
    看看上周的那个DefaultWorkflowInterceptor是如何工作的:
protected String doIntercept(ActionInvocation invocation) throws Exception { // 取得要拦截的Action对象 Object action = invocation.getAction(); if (action instanceof Validateable) { /* * 如果action是Validateable接口的一个实例,则执行接口的validate方法,
*这个方法可能是检查用户 * 输入的合法性,如果有错误,可能往errors里增加错误信息。 Validateable validateable = (Validateable) action; if (_log.isDebugEnabled()) { _log.debug("Invoking validate() on action "+validateable); } try { PrefixMethodInvocationUtil.invokePrefixMethod( invocation, new String[] { VALIDATE_PREFIX, ALT_VALIDATE_PREFIX }); } catch(Exception e) { e.printStackTrace(); // If any exception occurred while doing reflection, we want // validate() to be executed _log.warn("an exception occured while executing the prefix method", e); } if (alwaysInvokeValidate) { validateable.validate(); } } /* * 如果action是ValidationAware的实例,则检查action中是否包含错误信息,如果有,则返回 * INPUT的Result代码,并且整个Action就终止。
*/
if (action instanceof ValidationAware) { ValidationAware validationAwareAction = (ValidationAware) action; if (validationAwareAction.hasErrors()) { if (_log.isDebugEnabled()) { _log.debug("Errors on action "+validationAwareAction+",
returning result name 'input'
"); }
return Action.INPUT; }
}
/* * 输入合法,执行action的功能。 */ return invocation.invoke(); }
0
相关文章