点石互动

导航

 
前言:Struts2的三大组件:动作、拦截器、数据转移。动作组件可能是我们日常中经常接触的。但是在后台默默无闻工作的拦截器,却是真正的核心。在Struts2中没有一个动作被单独调用,总是包含了一系列的拦截器在动作执行之前或之后执行。通过创建一个ActionInvocation的对象,封装了一系列被配置在动作之前或之后触发的拦截器。Struts2提供了一组强大的智能默认值,如defaultStack提供了一个常用的拦截器组合。做web应用时,整个系统的权限设置,日志控制,依靠拦截器可以很方便的的实现。

1.拦截器的原理:
1.1 总指挥ActionInvocation接口,是理解拦截器的关键。它控制着整个动作的执行,以及与之相关的拦截器栈的执行顺序。当struts2框架接收到一个request-->决定url映射到哪个动作-->这个动作的一个实例会被加入到一二新创建的ActionInvocation实例中-->通过xml配置发现那些触发器按么顺序触发.
Java代码 复制代码 收藏代码
  1. public interface ActionInvocation extends Serializable {
  2. Object getAction();
  3. boolean isExecuted();
  4. ActionContext getInvocationContext();
  5. ActionProxy getProxy();
  6. Result getResult() throws Exception;
  7. String getResultCode();
  8. void setResultCode(String resultCode);
  9. ValueStack getStack();
  10. void addPreResultListener(PreResultListener listener);
  11. /**
  12. * Invokes the next step in processing this ActionInvocation.
  13. * <p/>
  14. * If there are more Interceptors, this will call the next one. If Interceptors choose not to short-circuit
  15. * ActionInvocation processing and return their own return code, they will call invoke() to allow the next Interceptor
  16. * to execute. If there are no more Interceptors to be applied, the Action is executed.
  17. * If the {@link ActionProxy#getExecuteResult()} method returns <tt>true</tt>, the Result is also executed.
  18. *
  19. * @throws Exception can be thrown.
  20. * @return the return code.
  21. */
  22. String invoke() throws Exception;
  23. String invokeActionOnly() throws Exception;
  24. void setActionEventListener(ActionEventListener listener);
  25. void init(ActionProxy proxy) ;
  26. }

框架通过调用ActionInvocation的invoke方法开始动作的执行,但并不总是映射到第一个拦截器,ActinInvocation负责跟踪执行的状态,并且把控制交给合适的拦截器。通过调用拦截器的intercept()方法将控制交给拦截器。.实际应用中编写的拦截器要实现Interceptor接口,通过intercept()方法返回的控制字符串决定页面的跳转,实现登录,权限控制。这就是拦截器的原理。
Java代码 复制代码 收藏代码
  1. public interface Interceptor extends Serializable {
  2. void destroy();
  3. void init();
  4. /**
  5. * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
  6. * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code.
  7. *
  8. * @param invocation the action invocation
  9. * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself.
  10. * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}.
  11. */
  12. String intercept(ActionInvocation invocation) throws Exception;
  13. }  
posted on 2013-02-19 21:15  点石互动  阅读(172)  评论(0编辑  收藏  举报