struts2源码分析及拦截器实现原理

来源:互联网 发布:c语言a =b 编辑:程序博客网 时间:2024/06/11 13:57

一:拦截器interceptor简介

拦截器interceptor是struts2中的最重要的核心之一,Struts2最强大的特性之一。拦截器可以让你在Actionresult被执行之前或之后进行一些处理。同时,拦截器也可以让你将通用的代码模块化并作为可重用的类。Struts2中的很多特性都是由拦截器来完成的拦截是AOP的一种实现策略。在Webwork的中文文档的解释为拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。谈到拦截器,还有一个词大家应该知道——拦截器链(Interceptor Chain,在Struts 2中称为拦截器栈Interceptor Stack)。拦截器链就是将拦截器按一定的顺序联结成一条链。在访问被拦截的方法或字段时,拦截器链中的拦截器就会按其之前定义的顺序被调用(这里借鉴引用他人总结)。

二:struts2实现原理(源码剖析)

struts2整个执行过程大致如下图所示:


下图是在debug跟踪的一个执行过程(由下往上执行顺序):




通过上图可以看出,struts2请求处理的一个过程:

1、客户端发起request请求action请求到达StrutsPrepareAndExecuteFilter的doFilter方法:

/* * $Id: DefaultActionSupport.java 651946 2008-04-27 13:41:38Z apetrelli $ * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *  http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. */package org.apache.struts2.dispatcher.ng.filter;import org.apache.struts2.StrutsStatics;import org.apache.struts2.dispatcher.Dispatcher;import org.apache.struts2.dispatcher.mapper.ActionMapping;import org.apache.struts2.dispatcher.ng.ExecuteOperations;import org.apache.struts2.dispatcher.ng.InitOperations;import org.apache.struts2.dispatcher.ng.PrepareOperations;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.util.List;import java.util.regex.Pattern;/** * Handles both the preparation and execution phases of the Struts dispatching process.  This filter is better to use * when you don't have another filter that needs access to action context information, such as Sitemesh. */public class StrutsPrepareAndExecuteFilter implements StrutsStatics, Filter {    protected PrepareOperations prepare;    protected ExecuteOperations execute;    protected List<Pattern> excludedPatterns = null;    public void init(FilterConfig filterConfig) throws ServletException {        InitOperations init = new InitOperations();        Dispatcher dispatcher = null;        try {            FilterHostConfig config = new FilterHostConfig(filterConfig);            init.initLogging(config);            dispatcher = init.initDispatcher(config);            init.initStaticContentLoader(config, dispatcher);            prepare = new PrepareOperations(dispatcher);            execute = new ExecuteOperations(dispatcher);            this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);            postInit(dispatcher, filterConfig);        } finally {            if (dispatcher != null) {                dispatcher.cleanUpAfterInit();            }            init.cleanup();        }    }    /**     * Callback for post initialization     */    protected void postInit(Dispatcher dispatcher, FilterConfig filterConfig) {    }    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {        HttpServletRequest request = (HttpServletRequest) req;        HttpServletResponse response = (HttpServletResponse) res;        try {            if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {                chain.doFilter(request, response);            } else {                prepare.setEncodingAndLocale(request, response);                prepare.createActionContext(request, response);                prepare.assignDispatcherToThread();                request = prepare.wrapRequest(request);                ActionMapping mapping = prepare.findActionMapping(request, response, true);                if (mapping == null) {                    boolean handled = execute.executeStaticResourceRequest(request, response);                    if (!handled) {                        chain.doFilter(request, response);                    }                } else {
<span style="white-space:pre"></span><span style="color:#ff6600;">//这里实际调用了dispatcher.java的serviceAction方法</span>                    execute.executeAction(request, response, mapping);                }            }        } finally {            prepare.cleanupRequest(request);        }    }    public void destroy() {        prepare.cleanupDispatcher();    }}

2、通过execute.executeAction(request, response, mapping); 调用Dispatcher.java的serviceAction方法:

<pre name="code" class="java"> public void serviceAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)            throws ServletException {        Map<String, Object> extraContext = createContextMap(request, response, mapping);        // 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();<span style="white-space:pre"></span><span style="color:#ff6600;">//通过动态代理,创建出一个ActionProxy对象</span>            ActionProxy proxy = 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 {           <span style="color:#ff6600;"> //调用execute方法</span>                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) {            logConfigurationException(request, e);            sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);        } catch (Exception e) {            if (handleException || devMode) {                sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);            } else {                throw new ServletException(e);            }        } finally {            UtilTimerStack.pop(timerKey);        }    }


3、通过动态代理,创建一个ActionProxy的对象,然后调用ActionProxy对象的execute方法:

<pre name="code" class="java" style="line-height: 26px;">ActionProxy对象是创建action的关键对象
<pre name="code" class="java">public String execute() throws Exception {        ActionContext nestedContext = ActionContext.getContext();
        ActionContext.setContext(invocation.getInvocationContext());        String retCode = null;        String profileKey = "execute: ";        try {            UtilTimerStack.push(profileKey);<span style="white-space:pre"></span><span style="color:#ff6600;">//调用了ActionInvocation的invoke方法</span>            retCode = invocation.invoke();        } finally {            if (cleanupContext) {                ActionContext.setContext(nestedContext);            }            UtilTimerStack.pop(profileKey);        }        return retCode;    }

4、通过ActionProxy的execute方法调用了ActionInvocation的invoke方法,这是实现拦截器的核心,ActionInvocationAction调度者

<pre name="code" class="java"> 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 = interceptors.next();                String interceptorMsg = "interceptor: " + interceptor.getName();                UtilTimerStack.push(interceptorMsg);                try {
<span style="white-space:pre"></span>//调用interceptor的intercept方法                                resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);                            }                finally {                    UtilTimerStack.pop(interceptorMsg);                }            } else {
<span style="white-space:pre"></span>//执行完默认的intercept方法后调用我们的action                resultCode = invokeActionOnly();            }

拦截器部分的执行调用:resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);

在这个实现类中,实际上已经实现了最简单的拦截器的雏形。这里需要指出的是一个很重要的方法invocation.invoke()。这是ActionInvocation中的方法,而ActionInvocation是Action调度者,所以这个方法具备以下2层含义:

1. 如果拦截器堆栈中还有其他的Interceptor,那么invocation.invoke()将调用堆栈中下一个Interceptor的执行。
2. 如果拦截器堆栈中只有Action了,那么invocation.invoke()将调用Action执行。


    所以,我们可以发现,invocation.invoke()这个方法其实是整个拦截器框架的实现核心。基于这样的实现机制,我们还可以得到下面2个非常重要的推论:
1. 如果在拦截器中,我们不使用invocation.invoke()来完成堆栈中下一个元素的调用,而是直接返回一个字符串作为执行结果,那么整个执行将被中止。
2. 我们可以以invocation.invoke()为界,将拦截器中的代码分成2个部分,在invocation.invoke()之前的代码,将会在Action之前被依次执行,而在invocation.invoke()之后的代码,将会在Action之后被逆序执行。
由此,我们就可以通过invocation.invoke()作为Action代码真正的拦截点,从而实现AOP。


5、通过遍历/struts-default.xml中一系列的intercept参数,调用interceptor的intercept方法:

<pre name="code" class="java"> public String intercept(ActionInvocation invocation) throws Exception {        String result;        try {
<span style="white-space:pre"></span><span style="color:#ff6600;">//这里又调用ActionInvocation的invoke方法</span>            result = invocation.invoke();        } catch (Exception e) {            if (isLogEnabled()) {                handleLogging(e);            }            List<ExceptionMappingConfig> exceptionMappings = invocation.getProxy().getConfig().getExceptionMappings();            ExceptionMappingConfig mappingConfig = this.findMappingFromExceptions(exceptionMappings, e);            if (mappingConfig != null && mappingConfig.getResult()!=null) {                Map parameterMap = mappingConfig.getParams();                // create a mutable HashMap since some interceptors will remove parameters, and parameterMap is immutable                invocation.getInvocationContext().setParameters(new HashMap<String, Object>(parameterMap));                result = mappingConfig.getResult();                publishException(invocation, new ExceptionHolder(e));            } else {                throw e;            }        }        return result;    }
原来在intercept()方法又对ActionInvocationinvoke()方法进行递归调用,ActionInvocation循环嵌套在intercept()中,一直到语句result = invocation.invoke()执行结束。这样,Interceptor又会按照刚开始执行的逆向顺序依次执行结束。一个有序链表,通过递归调用,变成了一个堆栈执行过程,将一段有序执行的代码变成了2段执行顺序完全相反的代码过程,从而巧妙地实现了AOP这也就成为了Struts2的Action层的AOP基础。


1 0
原创粉丝点击