struts2真正工作流程

1.客户端初始化一个请求,到一个servlet容器

2.经过ActionContextCleaUp->其他filters->FilterDispatcher

3.FilterDispatcher询问ActionMapper是否调用一个action处理,如果ActionMapper调用这个action处理request,则FilterDispatcher把请求转给ActionProxy,此时相当于Delegate-Dispatcher处理

4.ActionProxy根据ActionMapping和configManager(struts.xml)找到需要的Action类

5.ActionProxy创建一个ActionInvocation的实例,ActionInvocation实例初始化时,根据Action配置,加载相关拦截器,

ActionProxy通过代理模式调用Action的execute()方法,ActionProxy.execute();

execute方法为请求Action类的execute方法,ActionInvocation类invoke()方法会在execute()方法前面,后面添加拦截器,ActionInvocation.invoke()执行时,会先调用拦截器,再调用execute()方法,再调用拦截器,这就是典型的AOP

6.Action execute() 方法执行完毕,ActionInvocation会根据struts.xml配置找到对应的返回结果,如果要在return Result前做些其他的,可以在拦截器的PreResultListner类中实现

ActionInvocation代码如下:

package com.opensymphony.xwork2;

public interface ActionInvocation extends java.io.Serializable {
    
    java.lang.Object getAction();
    
    boolean isExecuted();
    
    com.opensymphony.xwork2.ActionContext getInvocationContext();
    
    com.opensymphony.xwork2.ActionProxy getProxy();
    
    com.opensymphony.xwork2.Result getResult() throws java.lang.Exception;
    
    java.lang.String getResultCode();
    
    void setResultCode(java.lang.String s);
    
    com.opensymphony.xwork2.util.ValueStack getStack();
    
    void addPreResultListener(com.opensymphony.xwork2.interceptor.PreResultListener preResultListener);
    
    java.lang.String invoke() throws java.lang.Exception;
    
    java.lang.String invokeActionOnly() throws java.lang.Exception;
    
    void setActionEventListener(com.opensymphony.xwork2.ActionEventListener actionEventListener);
    
    void init(com.opensymphony.xwork2.ActionProxy actionProxy);
    
    com.opensymphony.xwork2.ActionInvocation serialize();
    
    com.opensymphony.xwork2.ActionInvocation deserialize(com.opensymphony.xwork2.ActionContext actionContext);
}

7.FilterDispatcher初始化并启动doFilter()

代码如下:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException ...{   
        HttpServletRequest request = (HttpServletRequest) req;   
        HttpServletResponse response = (HttpServletResponse) res;   
        ServletContext servletContext = filterConfig.getServletContext();   
        // 在这里处理了HttpServletRequest和HttpServletResponse。   
        DispatcherUtils du = DispatcherUtils.getInstance();   
        du.prepare(request, response);//正如这个方法名字一样进行locale、encoding以及特殊request parameters设置   
        try ...{   
            request = du.wrapRequest(request, servletContext);//对request进行包装   
        } catch (IOException e) ...{   
            String message = "Could not wrap servlet request with MultipartRequestWrapper!";   
            LOG.error(message, e);   
            throw new ServletException(message, e);   
        }   
                ActionMapperIF mapper = ActionMapperFactory.getMapper();//得到action的mapper   
        ActionMapping mapping = mapper.getMapping(request);// 得到action 的 mapping   
        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 ("true".equals(Configuration.get(WebWorkConstants.WEBWORK_SERVE_STATIC_CONTENT))    
                    && resourcePath.startsWith("/webwork")) ...{   
                String name = resourcePath.substring("/webwork".length());   
                findStaticResource(name, response);   
            } else ...{   
                // this is a normal request, let it pass through   
                chain.doFilter(request, response);   
            }   
            // WW did its job here   
            return;   
        }   
        Object o = null;   
        try ...{   
            //setupContainer(request);   
            o = beforeActionInvocation(request, servletContext);   
           //整个框架最最核心的方法,下面分析   
            du.serviceAction(request, response, servletContext, mapping);   
        } finally ...{   
            afterActionInvocation(request, servletContext, o);   
            ActionContext.setContext(null);   
        }   
    }   
du.serviceAction(request, response, servletContext, mapping);   
//这个方法询问ActionMapper是否需要调用某个Action来处理这个(request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher把请求的处理交给ActionProxy   
public void serviceAction(HttpServletRequest request, HttpServletResponse response, String namespace, String actionName, Map requestMap, Map parameterMap, Map sessionMap, Map applicationMap) ...{    
        HashMap extraContext = createContextMap(requestMap, parameterMap, sessionMap, applicationMap, request, response, getServletConfig());  //实例化Map请求 ,询问ActionMapper是否需要调用某个Action来处理这个(request)请求   
        extraContext.put(SERVLET_DISPATCHER, this);    
        OgnlValueStack stack = (OgnlValueStack) request.getAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY);    
        if (stack != null) ...{    
            extraContext.put(ActionContext.VALUE_STACK,new OgnlValueStack(stack));    
        }    
        try ...{    
            ActionProxy proxy = ActionProxyFactory.getFactory().createActionProxy(namespace, actionName, extraContext);    
//这里actionName是通过两道getActionName解析出来的, FilterDispatcher把请求的处理交给ActionProxy,下面是ServletDispatcher的 TODO:    
            request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY, proxy.getInvocation().getStack());    
            proxy.execute();    
           //通过代理模式执行ActionProxy   
            if (stack != null)...{    
                request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY,stack);    
            }    
        } catch (ConfigurationException e) ...{    
            log.error("Could not find action", e);    
            sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);    
        } catch (Exception e) ...{    
            log.error("Could not execute action", e);    
            sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);    
        }    
}    

8.struts.xml配置文件代码如下:

<?xml version="1.0" encoding="GBK"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="strutsDemo" extends="struts-default">
        <action name="login" class="com.xx.LoginAction">
            <result>success.jsp</result>
        </action>
    </package>
    <include file="struts-default.xml"></include>
</struts>

9.struts-default.xml代码如下:

< interceptor name ="alias" class ="com.opensymphony.xwork2.interceptor.AliasInterceptor" />    
< interceptor name ="autowiring" class ="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor" />    
< interceptor name ="chain" class ="com.opensymphony.xwork2.interceptor.ChainingInterceptor" />    
< interceptor name ="conversionError" class ="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor" />    
< interceptor name ="createSession" class ="org.apache.struts2.interceptor.CreateSessionInterceptor" />    
< interceptor name ="debugging" class ="org.apache.struts2.interceptor.debugging.DebuggingInterceptor" />    
< interceptor name ="external-ref" class ="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor" />    
< interceptor name ="execAndWait" class ="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor" />    
< interceptor name ="exception" class ="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor" />    
< interceptor name ="fileUpload" class ="org.apache.struts2.interceptor.FileUploadInterceptor" />    
< interceptor name ="i18n" class ="com.opensymphony.xwork2.interceptor.I18nInterceptor" />    
< interceptor name ="logger" class ="com.opensymphony.xwork2.interceptor.LoggingInterceptor" />    
< interceptor name ="model-driven" class ="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor" />    
< interceptor name ="scoped-model-driven" class ="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor" />    
< interceptor name ="params" class ="com.opensymphony.xwork2.interceptor.ParametersInterceptor" />    
< interceptor name ="prepare" class ="com.opensymphony.xwork2.interceptor.PrepareInterceptor" />    
< interceptor name ="static-params" class ="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor" />    
< interceptor name ="scope" class ="org.apache.struts2.interceptor.ScopeInterceptor" />    
< interceptor name ="servlet-config" class ="org.apache.struts2.interceptor.ServletConfigInterceptor" />    
< interceptor name ="sessionAutowiring" class ="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor" />    
< interceptor name ="timer" class ="com.opensymphony.xwork2.interceptor.TimerInterceptor" />    
< interceptor name ="token" class ="org.apache.struts2.interceptor.TokenInterceptor" />    
< interceptor name ="token-session" class ="org.apache.struts2.interceptor.TokenSessionStoreInterceptor" />    
< interceptor name ="validation" class ="com.opensymphony.xwork2.validator.ValidationInterceptor" />    
< interceptor name ="workflow" class ="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor" />    
< interceptor name ="store" class ="org.apache.struts2.interceptor.MessageStoreInterceptor" />    
< interceptor name ="checkbox" class ="org.apache.struts2.interceptor.CheckboxInterceptor" />    
< interceptor name ="profiling" class ="org.apache.struts2.interceptor.ProfilingActivationInterceptor" />   



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值