Struts2对请求的处理过程

来源:互联网 发布:origin画图软件注册 编辑:程序博客网 时间:2024/05/17 20:30

Struts2对请求的处理过程

edited By Bruce Bob

我这里使用最简单的FilterDispatcher 进行分析,其实,从2.2以后,建议不要使用FilterDispatcher。而使用StrutsPrepareAndExecuteFilter。

直接看doFilter方法

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 lookfor 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 passthrough

                   chain.doFilter(request, response);

               }

                // The framework did its job here

                return;

            }

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

我们看到,首先,这里对request进行了简单的处理

request = prepareDispatcherAndWrapRequest(request,response);

这里主要是区分是否为文件上传,文件上传和其他的请求处理方式稍有区别。我们先不去关注,我们先把普通请求进行分析之后,在对文件上传进行分析。

mapping = actionMapper.getMapping(request,dispatcher.getConfigurationManager());

这里是通过对request中的 url进行分析,找到对应的actionMapping。

mapping是个简单的类,他内部存储了action的相关信息。

这里的处理也很简单,就是从config中获得所有的package对象并遍历,找出匹配的。

如果没有找到对应的mapping,可能是对静态资源的访问。如果是对struts中定义的静态资源的访问,则有资源加载器进行处理。否则,直接跳过过滤器,进入下一个过滤器。

如果找到对应的actionMapping,则通过dispatcher进行请求的处理。

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

进入该方法以后,首先执行了

Map<String, Object> extraContext =createContextMap(request, response, mapping, context);

该方法主要是将将所有的request,session,application中的attributes和参数整合到一个map中。为什么要这么做呢?这里就需要对struts2的设计思想简单说一下了。struts2是要将框架和容器进行分离的一个设计。所以,struts2不仅仅是可以应用于web开发,也适用于其他程序的开发,比如桌面应用。如果在他的处理过程中,出现对httpservletrequest等的依赖,那么,框架势必不能进行普通应用程序的开发。所以。为了减少对容器的依赖,这里将request,response等解析到map中。然后交给xwork进行处理。这里简单理解。回头我们还要对xwork进行详细的分析。

//对对应的action的处理

          //(高潮要来了!!)

String namespace =mapping.getNamespace();

String name =mapping.getName();

           String method = mapping.getMethod();

 

           Configuration config = configurationManager.getConfiguration();

            //生成代理的主要原因应该是将拦截器的调用加进来。

            //生成工厂类实例的方式是通过XWork中的IOC来进行了。            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 aresult, do it!

            if(mapping.getResult() !=null) {

               Result result = mapping.getResult();

               result.execute(proxy.getInvocation());

           } else {

               proxy.execute();

           }

这里呢,通过config.getContainer().getInstance(ActionProxyFactory.class)

获得actionproxy的工厂类,然后生成一个actionProxy的实例。熟悉spring的朋友应该知道,这里和spring的IOC很像。这里其实是通过Xwork的IOC来实现的。我们这里只需要知道通过config.getContainer() 能获得IOC容器。然后调用 getInstance(class)就能获得实例就好。具体的Xwork的IOC的实现,我们将会拿出专门的文章来进行分析。

这里为什么要生成一个actionProxy呢?从名字上看,当然是要对action进行代理了。我们知道,代理通常都是为了通过代理做不能做的事儿(比如说翻墙)或者是对要对代理的内容进行增强才做代理的。那这个代理是干什么用的?我们来看一下actionProxy的源码吧。

这里看起来比较简单:

retCode= invocation.invoke();

很明显,逻辑都放在ActionInvocation的实现类中了。该接口代表一个action的执行状态,他持有所有的拦截器和action实例。他通过重复的进入invoke方法执行。最开始是执行actionProxy,然后是拦截器,最后执行action。

if (interceptors.hasNext()) {

              //注意Interceptor的调用方式是递归,所以最后在拦截器执行完毕之后,肯定执行invokeActionOnly

                finalInterceptorMapping 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();

           }

为什么说这里是递归调用呢。我们看一下一个简单的interceptor实现就知道了。这里我们看一下ClearSessionInterceptor :

  public String intercept(ActionInvocation invocation)throws Exception {

        LOG.debug("Clearing HttpSession");

        ActionContext ac =invocation.getInvocationContext();

        Map session = ac.getSession();

 

        if (null != session) {

           session.clear();

        }

        returninvocation.invoke();

   }

拦截器中先执行自己拦截器自己的逻辑,然后通过传递将来的actionInvocation调用 invoke方法。在ActionInvocation中是通过 interceptors.hasNext()来遍历所有的拦截器的。当所有的拦截器执行完毕,调用invokeActionOnly() 方法正式进入action中。

在下面就是对函数执行结果的处理了。分为result类型和String类型。我们就先分析最常见的String类型的。至于其他的处理结果类型,我们稍后再做分析。