1.拦截器的原理:
1.1 总指挥ActionInvocation接口,是理解拦截器的关键。它控制着整个动作的执行,以及与之相关的拦截器栈的执行顺序。当struts2框架接收到一个request-->决定url映射到哪个动作-->这个动作的一个实例会被加入到一二新创建的ActionInvocation实例中-->通过xml配置发现那些触发器按么顺序触发.
- public interface ActionInvocation extends Serializable {
- Object getAction();
- boolean isExecuted();
- ActionContext getInvocationContext();
- ActionProxy getProxy();
- Result getResult() throws Exception;
- String getResultCode();
- void setResultCode(String resultCode);
- ValueStack getStack();
- void addPreResultListener(PreResultListener listener);
- /**
- * Invokes the next step in processing this ActionInvocation.
- * <p/>
- * If there are more Interceptors, this will call the next one. If Interceptors choose not to short-circuit
- * ActionInvocation processing and return their own return code, they will call invoke() to allow the next Interceptor
- * to execute. If there are no more Interceptors to be applied, the Action is executed.
- * If the {@link ActionProxy#getExecuteResult()} method returns <tt>true</tt>, the Result is also executed.
- *
- * @throws Exception can be thrown.
- * @return the return code.
- */
- String invoke() throws Exception;
- String invokeActionOnly() throws Exception;
- void setActionEventListener(ActionEventListener listener);
- void init(ActionProxy proxy) ;
- }
框架通过调用ActionInvocation的invoke方法开始动作的执行,但并不总是映射到第一个拦截器,ActinInvocation负责跟踪执行的状态,并且把控制交给合适的拦截器。通过调用拦截器的intercept()方法将控制交给拦截器。.实际应用中编写的拦截器要实现Interceptor接口,通过intercept()方法返回的控制字符串决定页面的跳转,实现登录,权限控制。这就是拦截器的原理。
- public interface Interceptor extends Serializable {
- void destroy();
- void init();
- /**
- * Allows the Interceptor to do some processing on the request before and/or after the rest of the processing of the
- * request by the {@link ActionInvocation} or to short-circuit the processing and just return a String return code.
- *
- * @param invocation the action invocation
- * @return the return code, either returned from {@link ActionInvocation#invoke()}, or from the interceptor itself.
- * @throws Exception any system-level error, as defined in {@link com.opensymphony.xwork2.Action#execute()}.
- */
- String intercept(ActionInvocation invocation) throws Exception;
- }