第三节:职责链模式——在SpringMVC源码分析

一、职责链模式在 SpringMVC 框架应用的源码分析

  1、SpringMVC—HandlerExecutionChain 类就使用到职责链模式

  2、SpringMVC 请求流程简图

  3、代码分析&说明

  代码:

 1 public class ResponsibilityChainTest {
 2     public static void main(String[] args) {
 3 
 4         // DispatcherServlet
 5 
 6         //说明
 7         /**
 8          *
 9          *  protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
10          *   HandlerExecutionChain mappedHandler = null;
11          *   mappedHandler = getHandler(processedRequest);//获取到HandlerExecutionChain对象
12          *    //在 mappedHandler.applyPreHandle 内部 得到啦 HandlerInterceptor interceptor
13          *    //调用了拦截器的  interceptor.preHandle
14          *   if (!mappedHandler.applyPreHandle(processedRequest, response)) {
15                     return;
16                 }
17 
18               //说明:mappedHandler.applyPostHandle 方法内部获取到拦截器,并调用
19               //拦截器的  interceptor.postHandle(request, response, this.handler, mv);
20              mappedHandler.applyPostHandle(processedRequest, response, mv);
21          *  }
22          *
23          *
24          *  //说明:在  mappedHandler.applyPreHandle内部中,
25          *  还调用了  triggerAfterCompletion 方法,该方法中调用了
26          *  HandlerInterceptor interceptor = getInterceptors()[i];
27             try {
28                 interceptor.afterCompletion(request, response, this.handler, ex);
29             }
30             catch (Throwable ex2) {
31                 logger.error("HandlerInterceptor.afterCompletion threw exception", ex2);
32             }
33          */
34 
35     }
36 }

  说明:

    (1)SpringMVC 请求的流程图中,执行了拦截器相关方法 intercept.preHandler 等等;

    (2)在处理SpringMVC 请求时,使用到职责链模式还使用到适配器模式;

    (3)HandlerExecutionChain 主要负责的是请求拦截器的执行和请求处理,但是他本身不处理请求,只是将请求分配给链上注册处理器执行,这是职责链实现方式,减少职责链本身与处理逻辑之间的耦合,规范了处理流程;

    (4)HandlerExecutionChain 维护了 HandlerInterceptor 的集合,可以向其中注册响应的拦截器。

原文地址:https://www.cnblogs.com/niujifei/p/14490074.html