拦截器是struts2处理的核心,本文主要说struts2的拦截器的基本原理/实现,其它框架处理的东西就不说了,得自己再看了。
struts2版本:2.2.3
当一个请求来了后,从org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter 开始处理

     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

try {
           //设置编码
            prepare.setEncodingAndLocale(request, response);
            //创建actionContext
            prepare.createActionContext(request, response);
            prepare.assignDispatcherToThread();

//如果不是struts的请求则继续由其它过滤器执行

if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
                chain.doFilter(request, response);
            } else {

//包装request,对有文件上传的特殊处理下

request = prepare.wrapRequest(request);

//查找对应的ActionMapping

ActionMapping mapping = prepare.findActionMapping(request, response, true);

//如果找不到ActionMapping则当作静态资源来处理

if (mapping == null) {
                    boolean handled = execute.executeStaticResourceRequest(request, response);
                    if (!handled) {
                        chain.doFilter(request, response);
                    }
                } else {

//使用ActionMapping来执行action

execute.executeAction(request, response, mapping);
                }
            }
        } finally {
            prepare.cleanupRequest(request);
        }
    }

跟踪execute.executeAction(),则到了 org.apache.struts2.dispatcher.Dispatcher,如下:

     public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
                              ActionMapping mapping) throws ServletException {
        Map<String, Object> extraContext = createContextMap(request, response, mapping, context);

// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
        ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
        boolean nullStack = stack == null;
        if (nullStack) {
            ActionContext ctx = ActionContext.getContext();
            if (ctx != null) {
                stack = ctx.getValueStack();
            }
        }
        if (stack != null) {
            extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
        }

String timerKey = "Handling request from Dispatcher";
        try {
            UtilTimerStack.push(timerKey);
            String namespace = mapping.getNamespace();
            String name = mapping.getName();
            String method = mapping.getMethod();

Configuration config = configurationManager.getConfiguration();

   //使用StrutsActionProxyFactory(ActionProxyFactory的一个实现)创建action代理对象
   //proxy实际上是org.apache.struts2.impl.StrutsActionProxy类型

ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
                    namespace, name, method, extraContext, true, false);

request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());

// if the ActionMapping says to go straight to a result, do it!
            if (mapping.getResult() != null) {
                Result result = mapping.getResult();
                result.execute(proxy.getInvocation());
            } else {

//执行action

proxy.execute();
            }

// If there was a previous value stack then set it back onto the request
            if (!nullStack) {
                request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
            }
        } catch (ConfigurationException e) {
            // WW-2874 Only log error if in devMode
            if(devMode) {
                String reqStr = request.getRequestURI();
                if (request.getQueryString() != null) {
                    reqStr = reqStr + "?" + request.getQueryString();
                }
                LOG.error("Could not find action or result\n" + reqStr, e);
            }
            else {
                LOG.warn("Could not find action or result", e);
            }
            sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
        } catch (Exception e) {
            sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        } finally {
            UtilTimerStack.pop(timerKey);
        }
    }

DefaultActionProxyFactory创建ActionProxy,在com.opensymphony.xwork2.DefaultActionProxyFactory:

     public ActionProxy createActionProxy(String namespace, String actionName, String methodName, Map<String, Object> extraContext, boolean executeResult, boolean cleanupContext) {
        
        ActionInvocation inv = new DefaultActionInvocation(extraContext, true);
        container.inject(inv);
        return createActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);
    }

接下来看看 org.apache.struts2.impl.StrutsActionProxy的execute()方法,如下:

     public String execute() throws Exception {
        ActionContext previous = ActionContext.getContext();
        ActionContext.setContext(invocation.getInvocationContext());
        try {        //这里就是调用拦截器的入口了
            return invocation.invoke();
        } finally {
            if (cleanupContext)
                ActionContext.setContext(previous);
        }
    }

最关键的,com.opensymphony.xwork2.DefaultActionInvocation.invoke()方法,这个DefaultActionInvocation是ActionInvocation的一个实现类,如下:

  //保存了执行当前action方法时需要调用的拦截器栈,按照struts.xml中配制的拦截器顺序,从前到后,依次加入到了这个Iterator里面
  protected Iterator<InterceptorMapping> interceptors;

public String invoke() throws Exception {
        String profileKey = "invoke: ";
        try {
            UtilTimerStack.push(profileKey);

if (executed) {
                throw new IllegalStateException("Action has already executed");
            }
            //如果当前还有下一个,则继续执行拦截器
            if (interceptors.hasNext()) {
                final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
                String interceptorMsg = "interceptor: " + interceptor.getName();
                UtilTimerStack.push(interceptorMsg);
                try {

//执行拦截器的intercept()方法,并将当前ActionInvocation对象传递给这个方法
     //这样,当一个拦截器执行完自己的处理后,需要让框架继续执行下一个拦截器的时候,直接使用actionInvocation.invoke()方法,当前这个方法又会被调一次,这其实就是一个递归了,递归方法是ActionInvocation.invoke(),结束条件是interceptors.hasNext()

resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
                            }
                finally {
                    UtilTimerStack.pop(interceptorMsg);
                }
            } else { //拦截器全部都执行了,那么最后来执行action,跳出递归了
                resultCode = invokeActionOnly();
            }

// this is needed because the result will be executed, then control will return to the Interceptor, which will
            // return above and flow through again
            if (!executed) {
                if (preResultListeners != null) {
                    for (Object preResultListener : preResultListeners) {
                        PreResultListener listener = (PreResultListener) preResultListener;

String _profileKey = "preResultListener: ";
                        try {
                            UtilTimerStack.push(_profileKey);
                            listener.beforeResult(this, resultCode);
                        }
                        finally {
                            UtilTimerStack.pop(_profileKey);
                        }
                    }
                }

// now execute the result, if we're supposed to
                if (proxy.getExecuteResult()) {
                    executeResult();
                }

executed = true;
            }

return resultCode;
        }
        finally {
            UtilTimerStack.pop(profileKey);
        }
    }

基本原理到此为止,下面弄个小例子再说明一下:

//拦截器,相当于struts2的拦截器
 public interface Interceptor {
    String intercept(InvocationContext context);
}

//很多拦截器的实现
public class ExceptionInterceptor implements Interceptor {

public String intercept(InvocationContext context) {
        // 对异常的处理
        System.out.println("\t\t\tExceptionInterceptor 处理异常");
        return context.invoke();
    }
}
public class FileUploadInterceptor implements Interceptor {

public String intercept(InvocationContext context) {
        // 处理文件上传相关
        System.out.println("\t\t\tFileUploadInterceptor 处理文件上传");
        return context.invoke();
    }
}
public class ParameterInterceptor implements Interceptor {

public String intercept(InvocationContext context) {
        // 处理请求的参数
        System.out.println("\t\t\tParameterInterceptor 处理请求参数");
        return context.invoke();
    }
}


//执行拦截器的invocation上下文,相当于struts2的ActionInvocation
public class InvocationContext {

// 这里存放当前执行当前action所需要执行的拦截器栈
    private Iterator<Interceptor> interceptorIterator = null;
    private String prefix = "";

public InvocationContext() {
        // 模拟从配制文件中相应的规则取拦截器栈
        ArrayList<Interceptor> list = new ArrayList<Interceptor>();
        list.add(new ExceptionInterceptor());
        list.add(new FileUploadInterceptor());
        list.add(new ParameterInterceptor());
        interceptorIterator = list.iterator();
    }

public String invoke() {
        // 是否还有拦截器需要执行
        if (interceptorIterator.hasNext()) {
            // 获取下一个需要执行的拦截器
            Interceptor interceptor = interceptorIterator.next();
            String name = interceptor.getClass().getName();
            name = prefix + name;
            System.out.println(name + " intercept start...");
            prefix += "\t";
            // Interceptor的所有intercept方法实现里面,最后都调用了InvocationContext.invoke()方法
            // 其实就是一个递归,只不过invoke()的下一个递归是在Interceptor.intercept()里面调用的
            // 所以说为什么Interceptor.intercept()方法要加个InvocationContext的参数呢,作用就在于此
            String result = interceptor.intercept(this);
            System.out.println(name + " intercept end...");
            return result;
        } else {// 所有的拦截器都执行完了,那就来执行action对应的方法
            return executeAction();
        }
    }

private String executeAction() {
        System.out.println(prefix + "executeAction success.");
        return "success";
    }
}


//模拟请求进行测试
public class Test {

public static void main(String[] args) {
        InvocationContext context = new InvocationContext();
        System.out.println("请求开始了...");
        context.invoke();
        System.out.println("请求处理完了...");
    }
}

Struts2拦截器原理的更多相关文章

  1. Struts2拦截器原理以及实例

    一.Struts2拦截器定义 1. Struts2拦截器是在访问某个Action或Action的某个方法,字段之前或之后实施拦截,并且Struts2拦截器是可插拔的,拦截器是AOP的一种实现. 2. ...

  2. struts2 javaweb 过滤器、监听器 拦截器 原理

    转: 过滤器.监听器 拦截器 过滤器 创建一个 Filter 只需两个步骤: (1)创建 Filter 处理类: (2)在 web.xml 文件中配置 Filter . 创建 Filter 必须实现 ...

  3. 浅谈Struts2拦截器的原理与实现

    拦截器与过滤器           拦截器是对调用的Action起作用,它提供了一种机制可以使开发者定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行.同时也是提供了 ...

  4. Struts2拦截器详解

    一.Struts2拦截器原理: Struts2拦截器的实现原理相对简单,当请求struts2的action时,Struts 2会查找配置文件,并根据其配置实例化相对的    拦截器对象,然后串成一个列 ...

  5. struts2拦截器(四)

    struts2拦截器原理: 当请求action时,struts2会查找配置文件,并根据配置实例化相对的 拦截器对象,然后串成一个列表,然后一个一个的调用列表中的拦截器. 比如:某些页面必须登录才可以访 ...

  6. Struts2拦截器的使用 (详解)

    Struts2拦截器的使用 (详解) 如何使用struts2拦截器,或者自定义拦截器.特别注意,在使用拦截器的时候,在Action里面必须最后一定要引用struts2自带的拦截器缺省堆栈default ...

  7. Struts2拦截器模拟

    前言: 接触Struts2已经有一段时间,Student核心内容就是通过拦截器对接Action,实现View层的控制跳转.本文根据自身理解对Struts2进行一个Java实例的模拟,方便大家理解! 示 ...

  8. struts2拦截器interceptor的三种配置方法

    1.struts2拦截器interceptor的三种配置方法 方法1. 普通配置法 <struts> <package name="struts2" extend ...

  9. 从struts2拦截器到自定义拦截器

    拦截器可谓struts2的核心了,最基本的bean的注入就是通过默认的拦截器实现的,一般在struts2.xml的配置中,package内直接或间接继承了struts-default.xml,这样st ...

随机推荐

  1. WordPress企业建站心得

    回头聊聊我用WordPress做企业网站的事.说是企业网站,其实就是一个小的企业展示网站.事情要从我爸开了一家自行车店开始说起,自从他开了自行车店,不但开始学着玩起了微信(因为要做微信营销),又想到了 ...

  2. UVA 11600 Masud Rana(概率dp)

    当两个城市之间有安全的道路的时候,他们是互相可到达的,这种关系满足自反.对称和传递性, 因此是一个等价关系,在图论中就对应一个连通块. 在一个连通块中,当前点是那个并不影响往其他连通块的点连边,因此只 ...

  3. 【洛谷4884】多少个1?(BSGS)

    点此看题面 大致题意: 求满足\(个111...111(N\text{个}1)\equiv K(mod\ m)\)的最小\(N\). 题目来源 这题是洛谷某次极不良心的月赛的\(T1\),当时不会\( ...

  4. GMap.Net解决方案之在WinForm和WPF中使用GMap.Net地图插件的开发

    在做地理位置相关的开发时,总是面临高额地图引擎费用让大部分用户望而却步,加之地图数据又是天价,那么GMap.NET就是首选了,它本身就是开源免费,服务器可以在本地缓存,以后访问时就可以直接访问. 可以 ...

  5. iOS进阶面试题

    1. 风格纠错题 修改完的代码: 修改方法有很多种,现给出一种做示例: // .h文件 // http://weibo.com/luohanchenyilong/ // https://github. ...

  6. 【C++学习笔记】强大的算法——spfa

    spfa的定义 PFA算法的全称是:Shortest Path Faster Algorithm,用于求单源最短路,由西南交通大学段凡丁于1994年发表.当给定的图存在负边时,Dijkstra算法就无 ...

  7. 通过Tcode查找Badi或者客户出口

    https://wiki.scn.sap.com/wiki/display/ABAP/Code+To+Find+BAdi Created by Naresh Reddy K, last modifie ...

  8. shell脚本中case的用法

    shell脚本中case选择语句可以结合read指令实现比较好的交互应答操作,case接收到read指令传入的一个或多个参数,然后case根据参数做选择操作. case的语法如下 case $char ...

  9. 【CodeBase】通过层级键在多维数组中获取目标值

    通过层级键在多维数组中获取目标值 /* *Author : @YunGaZeon *Date : 2017.08.09 *param data : Data Array *param keys : K ...

  10. 虚拟机中配置SQL SERVER2008R2远程访问

    VM虚拟机中配置数据库访问 选择虚拟机设置--硬件--网络适配器,选择桥接模式:直接连接物理网络 不可选用主机模式(与主机共享专用网络) 数据库远程配置,转自:http://jingyan.baidu ...