struts2处理请求的过程



官方的流程图:


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

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

[java]  view plain  copy
  1.  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  2.   
  3.      HttpServletRequest request = (HttpServletRequest) req;  
  4.      HttpServletResponse response = (HttpServletResponse) res;  
  5.   
  6.      try {  
  7.          prepare.setEncodingAndLocale(request, response);  
  8.          prepare.createActionContext(request, response);  
  9.          prepare.assignDispatcherToThread();  
  10. if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {  
  11.     chain.doFilter(request, response);  
  12. else {  
  13.     request = prepare.wrapRequest(request);  
  14.     ActionMapping mapping = prepare.findActionMapping(request, response, true);  
  15.     if (mapping == null) {  
  16.         boolean handled = execute.executeStaticResourceRequest(request, response);  
  17.         if (!handled) {  
  18.             chain.doFilter(request, response);  
  19.         }  
  20.     } else {  
  21.         execute.executeAction(request, response, mapping);  
  22.     }  
  23. }  
  24.      } finally {  
  25.          prepare.cleanupRequest(request);  
  26.      }  
  27.  }  
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);方法。

[java]  view plain  copy
  1. public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,  
  2.                           ActionMapping mapping) throws ServletException {  
  3.   
  4.     Map<String, Object> extraContext = createContextMap(request, response, mapping, context);  
  5.   
  6.     // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action  
  7.     ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);  
  8.     boolean nullStack = stack == null;  
  9.     if (nullStack) {  
  10.         ActionContext ctx = ActionContext.getContext();  
  11.         if (ctx != null) {  
  12.             stack = ctx.getValueStack();  
  13.         }  
  14.     }  
  15.     if (stack != null) {  
  16.         extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));  
  17.     }  
  18.   
  19.     String timerKey = "Handling request from Dispatcher";  
  20.     try {  
  21.         UtilTimerStack.push(timerKey);  
  22.         String namespace = mapping.getNamespace();  
  23.         String name = mapping.getName();  
  24.         String method = mapping.getMethod();  
  25.   
  26.         Configuration config = configurationManager.getConfiguration();  
  27.         ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  28.                 namespace, name, method, extraContext, truefalse);  
  29.   
  30.         request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());  
  31.   
  32.         // if the ActionMapping says to go straight to a result, do it!  
  33.         if (mapping.getResult() != null) {  
  34.             Result result = mapping.getResult();  
  35.             result.execute(proxy.getInvocation());  
  36.         } else {  
  37.             proxy.execute();  
  38.         }  
  39.   
  40.         // If there was a previous value stack then set it back onto the request  
  41.         if (!nullStack) {  
  42.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);  
  43.         }  
  44.     } catch (ConfigurationException e) {  
  45.         // WW-2874 Only log error if in devMode  
  46.         if(devMode) {  
  47.             String reqStr = request.getRequestURI();  
  48.             if (request.getQueryString() != null) {  
  49.                 reqStr = reqStr + "?" + request.getQueryString();  
  50.             }  
  51.             LOG.error("Could not find action or result\n" + reqStr, e);  
  52.         }  
  53.         else {  
  54.             LOG.warn("Could not find action or result", e);  
  55.         }  
  56.         sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);  
  57.     } catch (Exception e) {  
  58.         sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);  
  59.     } finally {  
  60.         UtilTimerStack.pop(timerKey);  
  61.     }  
  62. }  

在这个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()方法,并转向结果;

[java]  view plain  copy
  1.     public String execute() throws Exception {  
  2.         ActionContext previous = ActionContext.getContext();  
  3.         ActionContext.setContext(invocation.getInvocationContext());  
  4.         try {  
  5. // This is for the new API:  
  6. //            return RequestContextImpl.callInContext(invocation, new Callable<String>() {  
  7. //                public String call() throws Exception {  
  8. //                    return invocation.invoke();  
  9. //                }  
  10. //            });  
  11.               
  12.             return invocation.invoke();  
  13.         } finally {  
  14.             if (cleanupContext)  
  15.                 ActionContext.setContext(previous);  
  16.         }  
  17.     }  

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

[java]  view plain  copy
  1. public String invoke() throws Exception {  
  2.     String profileKey = "invoke: ";  
  3.     try {  
  4.         UtilTimerStack.push(profileKey);  
  5.   
  6.         if (executed) {  
  7.             throw new IllegalStateException("Action has already executed");  
  8.         }  
  9.   
  10.         if (interceptors.hasNext()) {  
  11.             final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();  
  12.             String interceptorMsg = "interceptor: " + interceptor.getName();  
  13.             UtilTimerStack.push(interceptorMsg);  
  14.             try {  
  15.                             resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);  
  16.                         }  
  17.             finally {  
  18.                 UtilTimerStack.pop(interceptorMsg);  
  19.             }  
  20.         } else {  
  21.             resultCode = invokeActionOnly();  
  22.         }  
  23.   
  24.         // this is needed because the result will be executed, then control will return to the Interceptor, which will  
  25.         // return above and flow through again  
  26.         if (!executed) {  
  27.             if (preResultListeners != null) {  
  28.                 for (Object preResultListener : preResultListeners) {  
  29.                     PreResultListener listener = (PreResultListener) preResultListener;  
  30.   
  31.                     String _profileKey = "preResultListener: ";  
  32.                     try {  
  33.                         UtilTimerStack.push(_profileKey);  
  34.                         listener.beforeResult(this, resultCode);  
  35.                     }  
  36.                     finally {  
  37.                         UtilTimerStack.pop(_profileKey);  
  38.                     }  
  39.                 }  
  40.             }  
  41.   
  42.             // now execute the result, if we're supposed to  
  43.             if (proxy.getExecuteResult()) {  
  44.                 executeResult();  
  45.             }  
  46.   
  47.             executed = true;  
  48.         }  
  49.   
  50.         return resultCode;  
  51.     }  
  52.     finally {  
  53.         UtilTimerStack.pop(profileKey);  
  54.     }  
  55. }  

该方法实现了对 拦截器的递归调用 ,拦截器的实现采用了责任链模式,所有拦截器必须实现接口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;


官方的流程图:


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

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

[java]  view plain  copy
  1.  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  2.   
  3.      HttpServletRequest request = (HttpServletRequest) req;  
  4.      HttpServletResponse response = (HttpServletResponse) res;  
  5.   
  6.      try {  
  7.          prepare.setEncodingAndLocale(request, response);  
  8.          prepare.createActionContext(request, response);  
  9.          prepare.assignDispatcherToThread();  
  10. if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {  
  11.     chain.doFilter(request, response);  
  12. else {  
  13.     request = prepare.wrapRequest(request);  
  14.     ActionMapping mapping = prepare.findActionMapping(request, response, true);  
  15.     if (mapping == null) {  
  16.         boolean handled = execute.executeStaticResourceRequest(request, response);  
  17.         if (!handled) {  
  18.             chain.doFilter(request, response);  
  19.         }  
  20.     } else {  
  21.         execute.executeAction(request, response, mapping);  
  22.     }  
  23. }  
  24.      } finally {  
  25.          prepare.cleanupRequest(request);  
  26.      }  
  27.  }  
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);方法。

[java]  view plain  copy
  1. public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,  
  2.                           ActionMapping mapping) throws ServletException {  
  3.   
  4.     Map<String, Object> extraContext = createContextMap(request, response, mapping, context);  
  5.   
  6.     // If there was a previous value stack, then create a new copy and pass it in to be used by the new Action  
  7.     ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);  
  8.     boolean nullStack = stack == null;  
  9.     if (nullStack) {  
  10.         ActionContext ctx = ActionContext.getContext();  
  11.         if (ctx != null) {  
  12.             stack = ctx.getValueStack();  
  13.         }  
  14.     }  
  15.     if (stack != null) {  
  16.         extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));  
  17.     }  
  18.   
  19.     String timerKey = "Handling request from Dispatcher";  
  20.     try {  
  21.         UtilTimerStack.push(timerKey);  
  22.         String namespace = mapping.getNamespace();  
  23.         String name = mapping.getName();  
  24.         String method = mapping.getMethod();  
  25.   
  26.         Configuration config = configurationManager.getConfiguration();  
  27.         ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(  
  28.                 namespace, name, method, extraContext, truefalse);  
  29.   
  30.         request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());  
  31.   
  32.         // if the ActionMapping says to go straight to a result, do it!  
  33.         if (mapping.getResult() != null) {  
  34.             Result result = mapping.getResult();  
  35.             result.execute(proxy.getInvocation());  
  36.         } else {  
  37.             proxy.execute();  
  38.         }  
  39.   
  40.         // If there was a previous value stack then set it back onto the request  
  41.         if (!nullStack) {  
  42.             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);  
  43.         }  
  44.     } catch (ConfigurationException e) {  
  45.         // WW-2874 Only log error if in devMode  
  46.         if(devMode) {  
  47.             String reqStr = request.getRequestURI();  
  48.             if (request.getQueryString() != null) {  
  49.                 reqStr = reqStr + "?" + request.getQueryString();  
  50.             }  
  51.             LOG.error("Could not find action or result\n" + reqStr, e);  
  52.         }  
  53.         else {  
  54.             LOG.warn("Could not find action or result", e);  
  55.         }  
  56.         sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);  
  57.     } catch (Exception e) {  
  58.         sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);  
  59.     } finally {  
  60.         UtilTimerStack.pop(timerKey);  
  61.     }  
  62. }  

在这个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()方法,并转向结果;

[java]  view plain  copy
  1.     public String execute() throws Exception {  
  2.         ActionContext previous = ActionContext.getContext();  
  3.         ActionContext.setContext(invocation.getInvocationContext());  
  4.         try {  
  5. // This is for the new API:  
  6. //            return RequestContextImpl.callInContext(invocation, new Callable<String>() {  
  7. //                public String call() throws Exception {  
  8. //                    return invocation.invoke();  
  9. //                }  
  10. //            });  
  11.               
  12.             return invocation.invoke();  
  13.         } finally {  
  14.             if (cleanupContext)  
  15.                 ActionContext.setContext(previous);  
  16.         }  
  17.     }  

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

[java]  view plain  copy
  1. public String invoke() throws Exception {  
  2.     String profileKey = "invoke: ";  
  3.     try {  
  4.         UtilTimerStack.push(profileKey);  
  5.   
  6.         if (executed) {  
  7.             throw new IllegalStateException("Action has already executed");  
  8.         }  
  9.   
  10.         if (interceptors.hasNext()) {  
  11.             final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();  
  12.             String interceptorMsg = "interceptor: " + interceptor.getName();  
  13.             UtilTimerStack.push(interceptorMsg);  
  14.             try {  
  15.                             resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);  
  16.                         }  
  17.             finally {  
  18.                 UtilTimerStack.pop(interceptorMsg);  
  19.             }  
  20.         } else {  
  21.             resultCode = invokeActionOnly();  
  22.         }  
  23.   
  24.         // this is needed because the result will be executed, then control will return to the Interceptor, which will  
  25.         // return above and flow through again  
  26.         if (!executed) {  
  27.             if (preResultListeners != null) {  
  28.                 for (Object preResultListener : preResultListeners) {  
  29.                     PreResultListener listener = (PreResultListener) preResultListener;  
  30.   
  31.                     String _profileKey = "preResultListener: ";  
  32.                     try {  
  33.                         UtilTimerStack.push(_profileKey);  
  34.                         listener.beforeResult(this, resultCode);  
  35.                     }  
  36.                     finally {  
  37.                         UtilTimerStack.pop(_profileKey);  
  38.                     }  
  39.                 }  
  40.             }  
  41.   
  42.             // now execute the result, if we're supposed to  
  43.             if (proxy.getExecuteResult()) {  
  44.                 executeResult();  
  45.             }  
  46.   
  47.             executed = true;  
  48.         }  
  49.   
  50.         return resultCode;  
  51.     }  
  52.     finally {  
  53.         UtilTimerStack.pop(profileKey);  
  54.     }  
  55. }  

该方法实现了对 拦截器的递归调用 ,拦截器的实现采用了责任链模式,所有拦截器必须实现接口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;


  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值