struts2处理请求的过程


官方的流程图:


客户端对tomcat服务器发出请求,将请求封装成HttpRequest对象,并进行预处理操作(如设置编码等);

通过web.xml文件 找到struts2的前端控制器StrutsPrepareAndExcuteFilter,并调用doFilter()方法。

    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);
            prepare.createActionContext(request, response);
            prepare.assignDispatcherToThread();
			if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
				chain.doFilter(request, response);
			} else {
				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 {
					execute.executeAction(request, response, mapping);
				}
			}
        } finally {
            prepare.cleanupRequest(request);
        }
    }
doFilter中:

1、设置编码;

2、创建ActionContext,创建ValueStack对象。

3、对请求进行重新封装,根据请求内容的类型不同,返回不同的对象:
如果为multipart/form-data类型,则返回MultiPartRequestWrapper类型的对象,否则返回StrutsRequestWrapper类型的对象,MultiPartRequestWrapper是StrutsRequestWrapper的子类,而这两个类都是HttpServletRequest接口的实现。

4、根据请求request获取actionMapping对象

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

如果mapping为null,说明请求的不是Action,会调用execute.executeStaticResourceRequest(request, response);方法,请求静态资源。

如果mapping不为null,调用execute.executeAction(request, response, mapping),在这个方法中又调用

dispatcher.serviceAction(request, response, servletContext, mapping);方法。

    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();
            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 {
                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);
        }
    }

在这个serviceAction方法中,

1、将相关对象信息封装为Map(如:HttpServletRequest、Http parameters、HttpServletResponse、HttpSession、ServletContext、ActionMapping等对象信息),存入到执行上下文Map中,返回执行上下文Map对象extraMap;

2、获取ValueStack对象,并放入map中
3、获取mapping对象中存储的action命名空间、name属性、method属性等信息;
4、加载并解析Struts2配置文件,如果没有人为配置,默认按顺序加载struts-default.xml、struts-plugin.xml、struts.xml,将action配置、result配置、interceptor配置,解析并存入至config对象中,返回文件配置对象config;
5、 根据执行上下文Map、action命名空间、name属性、method属性等创建ActionProxy对象

createActionProxy()方法中:

5.1、创建invacation:ActionInvocation inv= new DefaultActionInvocation(extraContext, true);

5.2、创建proxy:DefaultActionProxy proxy = new DefaultActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);

5.3、接着,proxy.prepare();方法中

5.4、初始化action:invocation.init(this);方法中

使用反射创建action,并压入值栈栈顶,准备拦截器集合。

接着:

6、 执行ActionProxy对象的proxy.execute()方法,并转向结果;

    public String execute() throws Exception {
        ActionContext previous = ActionContext.getContext();
        ActionContext.setContext(invocation.getInvocationContext());
        try {
// This is for the new API:
//            return RequestContextImpl.callInContext(invocation, new Callable<String>() {
//                public String call() throws Exception {
//                    return invocation.invoke();
//                }
//            });
            
            return invocation.invoke();
        } finally {
            if (cleanupContext)
                ActionContext.setContext(previous);
        }
    }

该方法调用了invocation.invoke()方法。

    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 {
                                resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
                            }
                finally {
                    UtilTimerStack.pop(interceptorMsg);
                }
            } else {
                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);
        }
    }

该方法实现了对 拦截器的递归调用,拦截器的实现采用了责任链模式,所有拦截器必须实现接口Interceptor的intercept(ActionInvocation invocation)方法,该方法的参数为ActionInvocation,所以在方法最后调用invocation.invoke()方法就实现了拦截器的递归调用。

拦截器调用一遍,直到最后一个invoke()方法,拦截器列表中没有未执行的拦截器,这时,会执行action相应的方法,并得到resultCode,接着,在返回Result之前,会执行PreResultListener的beforeResult()方法 ,最后执行结果,找到resultCode对应的结果类型,生成result对象,根据result的信息,或者生成相应response,或者根据结果类型继续执行。最后,对于本次Action请求将相应的执行状态标志位设置,返回resultCode。

这时最后一个拦截器中的invoke()方法得到返回值,由于action和result相应的执行状态标志已经设置为执行过,所以通过上级拦截器中的invoke()方法将对下级拦截器的intercept()方法后的代码进行判断,action、result只执行一遍。然后拦截器由后往前返回,到此整个请求处理流程结束。


回顾整个流程:

a) 客户端初始化一个指向Servlet容器的请求;
b) 根据Web.xml配置,请求首先经过核心过滤器StrutsPrepareAndExcuteFilter,执行doFilter方法,在该方法中,这只编码,创建valuestack对象,询问ActionMapper来决定这个请求是否需要调用某个Action;如果ActionMapper决定需要调用某个Action,则ActionMapper会返回一个ActionMapping实例(存储Action的配置信息),调用executeAction()方法,

c)调用dispatcher.serviceAction()方法,创建ActionProxy(Action代理)对象,将请求交给代理对象继续处理;


d) ActionProxy对象根据ActionMapping和Configuration Manager询问框架的配置文件,找到需要调用的Action类;
e) ActionProxy对象创建时,会同时创建一个ActionInvocation的实例,并对action进行初始化,压入值栈栈顶;

f) 执行proxy.execute()方法,调用invocation.invoke()方法


f) ActionInvocation的invoke()方法中,在调用Action的过程前后,涉及到相关拦截器(Intercepter)的调用;
g) 一旦Action执行完毕,ActionInvocation实例负责根据struts.xml中的配置创建并返回Result。Result通常是一个需要被表示的JSP或者FreeMarker的模版,也可能是另外的一个Action链;
h) 如果要在返回Result之前做些什么,可以实现PreResultListener接口,PreResultListener可以在Interceptor中实现,也可以在Action中实现;
i) 根据Result对象信息,生成用户响应信息response,在生成响应过程中可以使用Struts2 框架中继承的标签,在此过程中仍会再次涉及到ActionMapper;




本文参考http://mktao.blog.51cto.com/5866429/978913


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Struts2 的启动流程大致包括以下几个步骤: 1. Web 容器加载配置文件:在 Web 容器如 Tomcat)启动时,它会 Struts2 的配置文件,其中包括 struts.xml 文件。 2. 创建 ServletContext 对象:Web 容器会创建一个 ServletContext 对象,用于保存整个 Web 应用的信息。 3. 初始化 Struts2 框架:Struts2 框架会在 ServletContext 对象创建后进行初始化。它会读取 struts.xml 配置文件,并根据配置信息创建必要的对象,如 Action 类、Interceptor 等。 4. 接收请求:当客户端发送请求时,Web 容器会根据 URL 映射规则将请求发送给 Struts2 的核心控制器——ActionServlet。 5. 拦截器链处理:ActionServlet 在接收到请求后,会通过拦截器链对请求进行处理。拦截器链是一系列拦截器的有序集合,每个拦截器可以在请求前后执行一些特定的操作。 6. 查找 Action:经过拦截器链的处理后,ActionServlet 会根据请求中的信息查找对应的 Action 类。 7. 执行 Action 方法:找到 Action 类后,Struts2 会调用相应的 Action 方法来处理请求。方法执行完成后,会返回一个结果字符串。 8. 结果处理:Action 方法执行完成后,Struts2 将根据方法的返回结果字符串查找对应的结果视图,并进行相应的处理。这可能包括渲染 JSP 页面、返回 JSON 数据等。 9. 响应客户端:最后,Struts2 将生成的响应结果返回给客户端,完成整个请求-响应过程。 以上是 Struts2 的简要启动流程,其中涉及到了配置文件的加载、对象初始化、拦截器链处理、Action 查找与执行等步骤。具体的细节会根据项目的配置和需求有所差异。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值