Struts2知识积累(2)_核心概念:拦截器
前言:Struts2的三大组件:动作、拦截器、数据转移。动作组件可能是我们日常中经常接触的。但是在后台默默无闻工作的拦截器,却是真正的核心。在Struts2中没有一个动作被单独调用,总是包含了一系列的拦截器在动作执行之前或之后执行。通过创建一个ActionInvocation的对象,封装了一系列被配置在动作之前或之后触发的拦截器。Struts2提供了一组强大的智能默认值,如defaultStack提供了一个常用的拦截器组合。做web应用时,整个系统的权限设置,日志控制,依靠拦截器可以很方便的的实现。
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) ;}
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;}
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="struts-default" abstract="true"> <result-types> <result-type name="chain" /></package></struts>
<!ELEMENT struts (package|include|bean|constant)*><!ELEMENT package (result-types?, interceptors?, default-interceptor-ref?, default-action-ref?, default-class-ref?, global-results?, global-exception-mappings?, action*)>
<package name="global" extends="struts-default" > <interceptors> <interceptor name="demoInterceptor" />