struts2请求处理过程源代码分析(1)

转载自:http://www.see-source.com/ 源码解析网 java

网上对于struts2请求处理流程的讲解仍是比较多的,有的仍是很是详细的,因此这里我就简单地将大概流程总结下,有了个大概印象后理解起源码就会有必定的思路了: web

struts2的请求处理过程其实是在初始化中加载的配置及容器的基础上,经过请求的url分析出命名空间、action名称、方法名称,在利用命名空间检索出该命名空间下配置的全部antion,在经过action名称找到具体的action,生成action实例,若是该action上配置了拦截器则依次调用拦截器,以后调用action中方法名称指定的方法,最后经过配置中的result返回相应视图。 express

版本:struts2-2.1.6  xwork-2.1.2 apache

下面就经过源码进行分析下: session

struts2中处理请求是经过过滤器org.apache.struts2.dispatcher.FilterDispatcher的doFilter()方法实现的,以下: app


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

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        ServletContext servletContext = getServletContext();

        String timerKey = "FilterDispatcher_doFilter: ";
        try {

            // FIXME: this should be refactored better to not duplicate work with the action invocation
            ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
            ActionContext ctx = new ActionContext(stack.getContext());
            ActionContext.setContext(ctx);

            UtilTimerStack.push(timerKey);
            request = prepareDispatcherAndWrapRequest(request, response);
            ActionMapping mapping;
            try {
                mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());
            } catch (Exception ex) {
                log.error("error getting ActionMapping", ex);
                dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
                return;
            }

            if (mapping == null) {
                // there is no action in this request, should we look for a static resource?
                String resourcePath = RequestUtils.getServletPath(request);

                if ("".equals(resourcePath) && null != request.getPathInfo()) {
                    resourcePath = request.getPathInfo();
                }

                if (staticResourceLoader.canHandle(resourcePath)) {
                    staticResourceLoader.findStaticResource(resourcePath, request, response);
                } else {
                    // this is a normal request, let it pass through
                    chain.doFilter(request, response);
                }
                // The framework did its job here
                return;
            }

            dispatcher.serviceAction(request, response, servletContext, mapping);

        } finally {
            try {
                ActionContextCleanUp.cleanUp(req);
            } finally {
                UtilTimerStack.pop(timerKey);
            }
        }
    }

前2句比较简单,向上转换req、res为标准接口HttpServletRequest、HttpServletResponse形式。req是org.apache.catalina.connector.RequestFacade的实例,RequestFacade实现了接口HttpServletRequest,而HttpServletRequest继承自ServletRequest接口。第3句,得到servletContext即servlet上下文,经过上下文对象能够访问web.xml描述文件的初始化参数。第4句定义timerKey变量,值是将当前过滤器的类名和当前方法名拼接起来,看下下面的代码发现timerKey用于UtilTimerStack.push(timerKey)和UtilTimerStack.pop(timerKey)俩句,其实这俩句并不属于处理流程的功能代码,而是性能代码,主要是监测下doFilter()方法的执行时间,而后经过日志打印出来,因此这俩句能够不用理会。ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack()句,首先经过dispatcher.getContainer().getInstance(ValueStackFactory.class)从容器中得到type(类型)为ValueStackFactory.class的bean,而后调用该bean的createValueStack()建立一个ValueStack实例。ValueStackFactory.class默认状况下是使用struts-default.xml配置中的 <bean type="com.opensymphony.xwork2.util.ValueStackFactory" name="struts" class="com.opensymphony.xwork2.ognl.OgnlValueStackFactory" />,即经过上面的容器返回的是个com.opensymphony.xwork2.ognl.OgnlValueStackFactory实例,从名字看出其是个ValueStack工厂,经过调用该工厂的createValueStack()方法返回ValueStack实例。 jsp

ValueStack就是一般所说的"值栈",系统每次请求时都会建立个新的ValueStack,其中会保存着本次请求处理的全部中间数据,如:请求的action实例、各类servlet内置对象(request、response、session、application等)、请求参数等。F5看下定义: ide


public interface ValueStack {

    public static final String VALUE_STACK = "com.opensymphony.xwork2.util.ValueStack.ValueStack";
    public static final String REPORT_ERRORS_ON_NO_PROP = "com.opensymphony.xwork2.util.ValueStack.ReportErrorsOnNoProp";
    public abstract Map<String, Object> getContext();
    public abstract void setDefaultType(Class defaultType);
    public abstract void setExprOverrides(Map<Object, Object> overrides);
    public abstract Map<Object, Object> getExprOverrides();
    public abstract CompoundRoot getRoot();
    public abstract void setValue(String expr, Object value);
    public abstract void setValue(String expr, Object value, boolean throwExceptionOnFailure);
    public abstract String findString(String expr);
    public abstract Object findValue(String expr);
    public abstract Object findValue(String expr, Class asType);
    public abstract Object peek();
    public abstract Object pop();
    public abstract void push(Object o);
    public abstract void set(String key, Object o);
    public abstract int size();

}
是个接口,由于ValueStack自己是堆栈,因此咱们看到peek()、pop()、push()等堆栈方法都是有的,其中有个最重要的方法getContext()和getRoot(),getContext()返回的是个Map<String, Object>类型,通常请求中的参数、servlet各类内置对象都是存放在这个Map中。getRoot()返回的就是堆栈数据实际存放的地方,peek()、pop()、push()都是基于其操做的。CompoundRoot是个堆栈类,它继承了java.util.ArrayList,并以此为基础实现了peek()、pop()、push()方法,从而能够独立的做为堆栈使用。这样的话ValueStack就没必要在单独实现堆栈功能,只须要在内部建立个CompoundRoot实例就可,其peek()、pop()、push()方法直接调用CompoundRoot的相应方法便可,实际上struts2中的 ValueStack默认实现类就是这样作的。另外在这个堆栈中保存的最典型的数据就是action实例。有ognl知识的朋友知道,ognl中基于搜索的有俩个重要对象:上下文和根对象,实际上struts2在利用ognl时,是将getContext()得到的对象做为ognl的上下文、getRoot()得到的做为根对象。这就是为何咱们在经过struts2标签访问action中属性数据时不须要加"#",而访问request、response、session中数据时须要加"#"的缘由了。由于ognl中访问根对象是不须要加"#"的,而访问上下文是须要加"#"的。为了更好的理解这块,建议你们先学习下ognl的使用方法及特性。为了验证上面的说法,我举个例子,看下struts2的<s:property value=""/>标签是如何使用ValueStack的,以及最后如何调用ognl的。


这里还要事先交代下,在处理流程的后面处理中会将ValueStack(引用)存于俩个地:一个是ActionContext,另外一个是经过request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, valuesStack)将ValueStack存于request中。<s:property value=""/>标签中使用的ValueStack是经过request得到的。下面看下<s:property value=""/>标签的源码,从struts2的标签订义文件struts-tags.tld中查到,该标签对应的类是org.apache.struts2.views.jsp.PropertyTag,以下: 性能


public class PropertyTag extends ComponentTagSupport {

    private static final long serialVersionUID = 435308349113743852L;

    private String defaultValue;
    private String value;
    private boolean escape = true;
    private boolean escapeJavaScript = false;

    public Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
        return new Property(stack);
    }

    protected void populateParams() {
        super.populateParams();

        Property tag = (Property) component;
        tag.setDefault(defaultValue);
        tag.setValue(value);
        tag.setEscape(escape);
        tag.setEscapeJavaScript(escapeJavaScript);
    }

    public void setDefault(String defaultValue) {
        this.defaultValue = defaultValue;
    }

    public void setEscape(boolean escape) {
        this.escape = escape;
    }

    public void setEscapeJavaScript(boolean escapeJavaScript) {
        this.escapeJavaScript = escapeJavaScript;
    }
    
    public void setValue(String value) {
        this.value = value;
    }
}
咱们要找下标签的doStartTag(),这个方法会在标签被处理前调用。关于标签这块,建议你们先学下jsp自定义标签的使用。 

去它的父类ComponentTagSupport中找下: 学习


public abstract class ComponentTagSupport extends StrutsBodyTagSupport {
    protected Component component;

    public abstract Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res);

    public int doEndTag() throws JspException {
        component.end(pageContext.getOut(), getBody());
        component = null;
        return EVAL_PAGE;
    }

    public int doStartTag() throws JspException {
        component = getBean(getStack(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse());
        Container container = Dispatcher.getInstance().getContainer();
        container.inject(component);
        
        populateParams();
        boolean evalBody = component.start(pageContext.getOut());

        if (evalBody) {
            return component.usesBody() ? EVAL_BODY_BUFFERED : EVAL_BODY_INCLUDE;
        } else {
            return SKIP_BODY;
        }
    }

    protected void populateParams() {
    }

    public Component getComponent() {
        return component;
    }
}

找到了。doStartTag()方法第1句,调用getBean(),其中有个参数调用了getStack(),实际上这个方法返回的就是我上面说的ValueStack。F5进入:


public class StrutsBodyTagSupport extends BodyTagSupport {

    private static final long serialVersionUID = -1201668454354226175L;

    protected ValueStack getStack() {
        return TagUtils.getStack(pageContext);
    }
    .
    .
    .
    //省略
}

该方法是在ComponentTagSupport的父类StrutsBodyTagSupport中。其中只有一句TagUtils.getStack(pageContext),pageContext就是servlet的页面上下文内置对象,F5进入TagUtils.getStack(pageContext):


public static ValueStack getStack(PageContext pageContext) {
        HttpServletRequest req = (HttpServletRequest) pageContext.getRequest();
        ValueStack stack = (ValueStack) req.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);

        if (stack == null) {

            HttpServletResponse res = (HttpServletResponse) pageContext.getResponse();
            Dispatcher du = Dispatcher.getInstance();
            if (du == null) {
                throw new ConfigurationException("The Struts dispatcher cannot be found.  This is usually caused by "+
                        "using Struts tags without the associated filter. Struts tags are only usable when the request "+
                        "has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.");
            }
            stack = du.getContainer().getInstance(ValueStackFactory.class).createValueStack();
            Map<String, Object> extraContext = du.createContextMap(new RequestMap(req),
                    req.getParameterMap(),
                    new SessionMap(req),
                    new ApplicationMap(pageContext.getServletContext()),
                    req,
                    res,
                    pageContext.getServletContext());
            extraContext.put(ServletActionContext.PAGE_CONTEXT, pageContext);
            stack.getContext().putAll(extraContext);
            req.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);

            // also tie this stack/context to the ThreadLocal
            ActionContext.setContext(new ActionContext(stack.getContext()));
        } else {
            // let's make sure that the current page context is in the action context
            Map<String, Object> context = stack.getContext();
            context.put(ServletActionContext.PAGE_CONTEXT, pageContext);

            AttributeMap attrMap = new AttributeMap(context);
            context.put("attr", attrMap);
        }

        return stack;
    }

方法第1句,经过页面上下文对象pageContext得到本次请求的request对象,第2句在经过req.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY)得到ValueStack,由于事先struts2已经经过request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, valuesStack)将ValueStack存于request的ServletActionContext.STRUTS_VALUESTACK_KEY属性中,因此经过第2句就能够得到ValueStack,直接return stack返回到ComponentTagSupport类的doStartTag()方法,以下(我在把代码粘下):


public int doStartTag() throws JspException {
        component = getBean(getStack(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse());
        Container container = Dispatcher.getInstance().getContainer();
        container.inject(component);
        
        populateParams();
        boolean evalBody = component.start(pageContext.getOut());

        if (evalBody) {
            return component.usesBody() ? EVAL_BODY_BUFFERED : EVAL_BODY_INCLUDE;
        } else {
            return SKIP_BODY;
        }
    }

执行完getStack()接着看getBean()方法,在ComponentTagSupport类中能够找到,getBean()方法被定义为抽象方法,因此具体的实现要在其子类PropertyTag中找,F5进入:


public Component getBean(ValueStack stack, HttpServletRequest req, HttpServletResponse res) {
        return new Property(stack);
    }

方法只有一句经过new 生成了Property实例,同时将stack做为构造参数传进去,这个stack就是咱们上面经过getStack()获得的ValueStack,执行完后程序会从新回到ComponentTagSupport类的doStartTag()方法,我把代码在粘下:


public int doStartTag() throws JspException {
        component = getBean(getStack(), (HttpServletRequest) pageContext.getRequest(), (HttpServletResponse) pageContext.getResponse());
        Container container = Dispatcher.getInstance().getContainer();
        container.inject(component);
        
        populateParams();
        boolean evalBody = component.start(pageContext.getOut());

        if (evalBody) {
            return component.usesBody() ? EVAL_BODY_BUFFERED : EVAL_BODY_INCLUDE;
        } else {
            return SKIP_BODY;
        }
    }

这样component中实际引用的就是Property实例,第二、3句,调用容器,经过container.inject(component)将Property中须要注入的属性赋值(带有@Inject标注的)。populateParams()句将标签属性添加到component相应属性中,如value、escape。核心在下面这句component.start(pageContext.getOut()),经过ognl访问ValueStack从而得到标签的value值,F5进入Property的start():


public boolean start(Writer writer) {
        boolean result = super.start(writer);

        String actualValue = null;

        if (value == null) {
            value = "top";
        }
        else {
        	value = stripExpressionIfAltSyntax(value);
        }

        // exception: don't call findString(), since we don't want the
        //            expression parsed in this one case. it really
        //            doesn't make sense, in fact.
        actualValue = (String) getStack().findValue(value, String.class);

        try {
            if (actualValue != null) {
                writer.write(prepare(actualValue));
            } else if (defaultValue != null) {
                writer.write(prepare(defaultValue));
            }
        } catch (IOException e) {
            LOG.info("Could not print out value '" + value + "'", e);
        }

        return result;
    }

直接看(String) getStack().findValue(value, String.class)  调用getStack()得到ValueStack,这个ValueStack实在Property实例生成时经过构造方法传入的。以后调用ValueStack的findValue()方法, 其中参数value就是<s:property value=""/>标签的value属性值。咱们在上面说过ValueStack的实现类默认使用的是com.opensymphony.xwork2.ognl.OgnlValueStack类,F5进入其findValue():


public Object findValue(String expr, Class asType) {
        try {
            if (expr == null) {
                return null;
            }

            if ((overrides != null) && overrides.containsKey(expr)) {
                expr = (String) overrides.get(expr);
            }

            Object value = ognlUtil.getValue(expr, context, root, asType);
            if (value != null) {
                return value;
            } else {
                return findInContext(expr);
            }
        } catch (OgnlException e) {
            return findInContext(expr);
        } catch (Exception e) {
            logLookupFailure(expr, e);

            return findInContext(expr);
        } finally {
            ReflectionContextState.clear(context);
        }
    }

直接看ognlUtil.getValue(expr, context, root, asType)句,能够看到content、root就是咱们上面说的ValueStack中getContext()和getRoot()方法中对应的属性值,咱们说过它分别对应ognl中的上下文和根对象。ognlUtil是com.opensymphony.xwork2.ognl.OgnlUtil类的实例,是struts2中用于操做ognl而单独封装的管理类, F5进入ognlUtil.getValue()方法:


public Object getValue(String name, Map<String, Object> context, Object root, Class resultType) throws OgnlException {
        return Ognl.getValue(compile(name), context, root, resultType);
    }
实际上,上面的方法只是将name作处理后直接调用ognl的getValue()方法。context做为ognl的上下文,root做为ognl的根对象,name是属性名。此时的root中就存放着当前action的实例。return返回的值就是<s:property value=""/>标签最终所得到的值。说道这熟悉ognl的应该已经明白了。