springMVC源码分析--AbstractHandlerMapping(二)

上一篇博客 springMVC源码分析--HandlerMapping(一)中我们简单的介绍了HandlerMapping,接下来我们介绍一下它的抽象实现类AbstractHandlerMapping


HandlerMapping中定义了方法getHandler(HttpServletRequest request),AbstractHandlerMapping中的实现如下:

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //获得一个HandlerExecutionChain  
  2.     @Override  
  3.     public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {  
  4.         //从实现类中获得HanlderMethod  
  5.         Object handler = getHandlerInternal(request);  
  6.         if (handler == null) {  
  7.             handler = getDefaultHandler();  
  8.         }  
  9.         if (handler == null) {  
  10.             return null;  
  11.         }  
  12.         // Bean name or resolved handler?  
  13.         if (handler instanceof String) {  
  14.             String handlerName = (String) handler;  
  15.             handler = getApplicationContext().getBean(handlerName);  
  16.         }  
  17.         //获得HandlerExecutionChain  
  18.         HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);  
  19.         if (CorsUtils.isCorsRequest(request)) {  
  20.             CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);  
  21.             CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);  
  22.             CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);  
  23.             executionChain = getCorsHandlerExecutionChain(request, executionChain, config);  
  24.         }  
  25.         return executionChain;  
  26.     }  
在getHandler方法中又出现了两个方法getHandlerInternal(request),在子类中实现,目的就是获取要执行的Controller。

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //模板方法,用于子类中实现,通过request去查找对应的执行方法HandlerMethod  
  2.     protected abstract Object getHandlerInternal(HttpServletRequest request) throws Exception;  

getHandlerExecutionChain就是创建一个HandlerExecutionChain实例,参数值就是handler和request。

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //  
  2.     protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {  
  3.         //如果没有获得则创建一个  
  4.         HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?  
  5.                 (HandlerExecutionChain) handler : new HandlerExecutionChain(handler));  
  6.         //获得IP地址及端口后的URL地址  
  7.         String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);  
  8.         //在HandlerExecutionChain中添加拦截器  
  9.         for (HandlerInterceptor interceptor : this.adaptedInterceptors) {  
  10.             if (interceptor instanceof MappedInterceptor) {  
  11.                 MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;  
  12.                 //根据lookupPath来获取Interceptor  
  13.                 if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {  
  14.                     chain.addInterceptor(mappedInterceptor.getInterceptor());  
  15.                 }  
  16.             }  
  17.             else {  
  18.                 chain.addInterceptor(interceptor);  
  19.             }  
  20.         }  
  21.         return chain;  
  22.     }  

AbstractHandlerMapping提供了设置不同HandlerMapping的执行顺序oder。

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //设置不同HandlerMapping实现类的执行顺序  
  2.     public final void setOrder(int order) {  
  3.       this.order = order;  
  4.     }  
  5.   
  6.     @Override  
  7.     public final int getOrder() {  
  8.       return this.order;  
  9.     }  

除了以上几个重要的方法外,AbstractHandlerMapping还提供了进行拦截器初始化的一些操作。

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. //初始化时调用,初始化一些基本信息,这里主要是初始化一些拦截器  
  2.     @Override  
  3.     protected void initApplicationContext() throws BeansException {  
  4.         extendInterceptors(this.interceptors);//添加或修车intercept,现在并没有具体实现  
  5.         detectMappedInterceptors(this.adaptedInterceptors);//将springMVC容器或者父容器中的所有MappedInterceptor类型的Bean添加到mappedInterceptors属性中  
  6.         initInterceptors();  
  7.     }  
  8.   
  9.     protected void extendInterceptors(List<Object> interceptors) {  
  10.     }  
  11.   
  12.     //将springMVC容器或者父容器中的所有MappedInterceptor类型的Bean添加到mappedInterceptors属性中  
  13.     protected void detectMappedInterceptors(List<HandlerInterceptor> mappedInterceptors) {  
  14.         mappedInterceptors.addAll(  
  15.                 BeanFactoryUtils.beansOfTypeIncludingAncestors(  
  16.                         getApplicationContext(), MappedInterceptor.classtruefalse).values());  
  17.     }  
  18.   
  19.     //初始化Interceptor,将interceptors属性里所包含的对象按类型添加到mappedInterceptors或者adaptedInterceptors中。  
  20.     protected void initInterceptors() {  
  21.         if (!this.interceptors.isEmpty()) {  
  22.             for (int i = 0; i < this.interceptors.size(); i++) {  
  23.                 Object interceptor = this.interceptors.get(i);  
  24.                 if (interceptor == null) {  
  25.                     throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null");  
  26.                 }  
  27.                 this.adaptedInterceptors.add(adaptInterceptor(interceptor));  
  28.             }  
  29.         }  
  30.     }  
  31.   
  32.     protected HandlerInterceptor adaptInterceptor(Object interceptor) {  
  33.         if (interceptor instanceof HandlerInterceptor) {  
  34.             return (HandlerInterceptor) interceptor;  
  35.         }  
  36.         else if (interceptor instanceof WebRequestInterceptor) {  
  37.             return new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor);  
  38.         }  
  39.         else {  
  40.             throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName());  
  41.         }  
  42.     }  
  43.   
  44.     protected final HandlerInterceptor[] getAdaptedInterceptors() {  
  45.         int count = this.adaptedInterceptors.size();  
  46.         return (count > 0 ? this.adaptedInterceptors.toArray(new HandlerInterceptor[count]) : null);  
  47.     }  
  48.   
  49.     protected final MappedInterceptor[] getMappedInterceptors() {  
  50.         List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>();  
  51.         for (HandlerInterceptor interceptor : this.adaptedInterceptors) {  
  52.             if (interceptor instanceof MappedInterceptor) {  
  53.                 mappedInterceptors.add((MappedInterceptor) interceptor);  
  54.             }  
  55.         }  
  56.         int count = mappedInterceptors.size();  
  57.         return (count > 0 ? mappedInterceptors.toArray(new MappedInterceptor[count]) : null);  
  58.     }  

总体来看AbstractHandlerMapping提供了抽象方法getHandlerInternal在子类中实现,根据获得的Handler及配置的拦截器Interceptor来生成HandlerExecutionChain。

完整的AbstractHandlerMapping源码如下:

[java]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport  
  2.         implements HandlerMapping, Ordered {  
  3.   
  4.     private int order = Integer.MAX_VALUE;  // default: same as non-Ordered  
  5.   
  6.     private Object defaultHandler;  
  7.   
  8.     private UrlPathHelper urlPathHelper = new UrlPathHelper();  
  9.   
  10.     private PathMatcher pathMatcher = new AntPathMatcher();  
  11.   
  12.     private final List<Object> interceptors = new ArrayList<Object>();  
  13.   
  14.     private final List<HandlerInterceptor> adaptedInterceptors = new ArrayList<HandlerInterceptor>();  
  15.   
  16.     private CorsProcessor corsProcessor = new DefaultCorsProcessor();  
  17.   
  18.     private final UrlBasedCorsConfigurationSource corsConfigSource = new UrlBasedCorsConfigurationSource();  
  19.   
  20.     //设置不同HandlerMapping实现类的执行顺序  
  21.     public final void setOrder(int order) {  
  22.       this.order = order;  
  23.     }  
  24.   
  25.     @Override  
  26.     public final int getOrder() {  
  27.       return this.order;  
  28.     }  
  29.   
  30.     public void setDefaultHandler(Object defaultHandler) {  
  31.         this.defaultHandler = defaultHandler;  
  32.     }  
  33.   
  34.     public Object getDefaultHandler() {  
  35.         return this.defaultHandler;  
  36.     }  
  37.       
  38.     public void setAlwaysUseFullPath(boolean alwaysUseFullPath) {  
  39.         this.urlPathHelper.setAlwaysUseFullPath(alwaysUseFullPath);  
  40.         this.corsConfigSource.setAlwaysUseFullPath(alwaysUseFullPath);  
  41.     }  
  42.   
  43.     public void setUrlDecode(boolean urlDecode) {  
  44.         this.urlPathHelper.setUrlDecode(urlDecode);  
  45.         this.corsConfigSource.setUrlDecode(urlDecode);  
  46.     }  
  47.   
  48.     public void setRemoveSemicolonContent(boolean removeSemicolonContent) {  
  49.         this.urlPathHelper.setRemoveSemicolonContent(removeSemicolonContent);  
  50.         this.corsConfigSource.setRemoveSemicolonContent(removeSemicolonContent);  
  51.     }  
  52.   
  53.     public void setUrlPathHelper(UrlPathHelper urlPathHelper) {  
  54.         Assert.notNull(urlPathHelper, "UrlPathHelper must not be null");  
  55.         this.urlPathHelper = urlPathHelper;  
  56.         this.corsConfigSource.setUrlPathHelper(urlPathHelper);  
  57.     }  
  58.       
  59.     public UrlPathHelper getUrlPathHelper() {  
  60.         return urlPathHelper;  
  61.     }  
  62.   
  63.     public void setPathMatcher(PathMatcher pathMatcher) {  
  64.         Assert.notNull(pathMatcher, "PathMatcher must not be null");  
  65.         this.pathMatcher = pathMatcher;  
  66.         this.corsConfigSource.setPathMatcher(pathMatcher);  
  67.     }  
  68.   
  69.     public PathMatcher getPathMatcher() {  
  70.         return this.pathMatcher;  
  71.     }  
  72.   
  73.     public void setInterceptors(Object[] interceptors) {  
  74.         this.interceptors.addAll(Arrays.asList(interceptors));  
  75.     }  
  76.   
  77.     public void setCorsProcessor(CorsProcessor corsProcessor) {  
  78.         Assert.notNull(corsProcessor, "CorsProcessor must not be null");  
  79.         this.corsProcessor = corsProcessor;  
  80.     }  
  81.   
  82.     /** 
  83.      * Return the configured {@link CorsProcessor}. 
  84.      */  
  85.     public CorsProcessor getCorsProcessor() {  
  86.         return this.corsProcessor;  
  87.     }  
  88.   
  89.     public void setCorsConfigurations(Map<String, CorsConfiguration> corsConfigurations) {  
  90.         this.corsConfigSource.setCorsConfigurations(corsConfigurations);  
  91.     }  
  92.   
  93.     /** 
  94.      * Get the CORS configuration. 
  95.      */  
  96.     public Map<String, CorsConfiguration> getCorsConfigurations() {  
  97.         return this.corsConfigSource.getCorsConfigurations();  
  98.     }  
  99.   
  100.     //初始化时调用,初始化一些基本信息,这里主要是初始化一些拦截器  
  101.     @Override  
  102.     protected void initApplicationContext() throws BeansException {  
  103.         extendInterceptors(this.interceptors);//添加或修车intercept,现在并没有具体实现  
  104.         detectMappedInterceptors(this.adaptedInterceptors);//将springMVC容器或者父容器中的所有MappedInterceptor类型的Bean添加到mappedInterceptors属性中  
  105.         initInterceptors();  
  106.     }  
  107.   
  108.     protected void extendInterceptors(List<Object> interceptors) {  
  109.     }  
  110.   
  111.     //将springMVC容器或者父容器中的所有MappedInterceptor类型的Bean添加到mappedInterceptors属性中  
  112.     protected void detectMappedInterceptors(List<HandlerInterceptor> mappedInterceptors) {  
  113.         mappedInterceptors.addAll(  
  114.                 BeanFactoryUtils.beansOfTypeIncludingAncestors(  
  115.                         getApplicationContext(), MappedInterceptor.classtruefalse).values());  
  116.     }  
  117.   
  118.     //初始化Interceptor,将interceptors属性里所包含的对象按类型添加到mappedInterceptors或者adaptedInterceptors中。  
  119.     protected void initInterceptors() {  
  120.         if (!this.interceptors.isEmpty()) {  
  121.             for (int i = 0; i < this.interceptors.size(); i++) {  
  122.                 Object interceptor = this.interceptors.get(i);  
  123.                 if (interceptor == null) {  
  124.                     throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null");  
  125.                 }  
  126.                 this.adaptedInterceptors.add(adaptInterceptor(interceptor));  
  127.             }  
  128.         }  
  129.     }  
  130.   
  131.     protected HandlerInterceptor adaptInterceptor(Object interceptor) {  
  132.         if (interceptor instanceof HandlerInterceptor) {  
  133.             return (HandlerInterceptor) interceptor;  
  134.         }  
  135.         else if (interceptor instanceof WebRequestInterceptor) {  
  136.             return new WebRequestHandlerInterceptorAdapter((WebRequestInterceptor) interceptor);  
  137.         }  
  138.         else {  
  139.             throw new IllegalArgumentException("Interceptor type not supported: " + interceptor.getClass().getName());  
  140.         }  
  141.     }  
  142.   
  143.     protected final HandlerInterceptor[] getAdaptedInterceptors() {  
  144.         int count = this.adaptedInterceptors.size();  
  145.         return (count > 0 ? this.adaptedInterceptors.toArray(new HandlerInterceptor[count]) : null);  
  146.     }  
  147.   
  148.     protected final MappedInterceptor[] getMappedInterceptors() {  
  149.         List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>();  
  150.         for (HandlerInterceptor interceptor : this.adaptedInterceptors) {  
  151.             if (interceptor instanceof MappedInterceptor) {  
  152.                 mappedInterceptors.add((MappedInterceptor) interceptor);  
  153.             }  
  154.         }  
  155.         int count = mappedInterceptors.size();  
  156.         return (count > 0 ? mappedInterceptors.toArray(new MappedInterceptor[count]) : null);  
  157.     }  
  158.   
  159.     //获得一个HandlerExecutionChain  
  160.     @Override  
  161.     public final HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {  
  162.         //从实现类中获得HanlderMethod  
  163.         Object handler = getHandlerInternal(request);  
  164.         if (handler == null) {  
  165.             handler = getDefaultHandler();  
  166.         }  
  167.         if (handler == null) {  
  168.             return null;  
  169.         }  
  170.         // Bean name or resolved handler?  
  171.         if (handler instanceof String) {  
  172.             String handlerName = (String) handler;  
  173.             handler = getApplicationContext().getBean(handlerName);  
  174.         }  
  175.         //获得HandlerExecutionChain  
  176.         HandlerExecutionChain executionChain = getHandlerExecutionChain(handler, request);  
  177.         if (CorsUtils.isCorsRequest(request)) {  
  178.             CorsConfiguration globalConfig = this.corsConfigSource.getCorsConfiguration(request);  
  179.             CorsConfiguration handlerConfig = getCorsConfiguration(handler, request);  
  180.             CorsConfiguration config = (globalConfig != null ? globalConfig.combine(handlerConfig) : handlerConfig);  
  181.             executionChain = getCorsHandlerExecutionChain(request, executionChain, config);  
  182.         }  
  183.         return executionChain;  
  184.     }  
  185.   
  186.     //模板方法,用于子类中实现,通过request去查找对应的执行方法HandlerMethod  
  187.     protected abstract Object getHandlerInternal(HttpServletRequest request) throws Exception;  
  188.   
  189.     //  
  190.     protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) {  
  191.         //如果没有获得则创建一个  
  192.         HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ?  
  193.                 (HandlerExecutionChain) handler : new HandlerExecutionChain(handler));  
  194.         //获得IP地址及端口后的URL地址  
  195.         String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);  
  196.         //在HandlerExecutionChain中添加拦截器  
  197.         for (HandlerInterceptor interceptor : this.adaptedInterceptors) {  
  198.             if (interceptor instanceof MappedInterceptor) {  
  199.                 MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;  
  200.                 //根据lookupPath来获取Interceptor  
  201.                 if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) {  
  202.                     chain.addInterceptor(mappedInterceptor.getInterceptor());  
  203.                 }  
  204.             }  
  205.             else {  
  206.                 chain.addInterceptor(interceptor);  
  207.             }  
  208.         }  
  209.         return chain;  
  210.     }  
  211.   
  212.     protected CorsConfiguration getCorsConfiguration(Object handler, HttpServletRequest request) {  
  213.         if (handler instanceof HandlerExecutionChain) {  
  214.             handler = ((HandlerExecutionChain) handler).getHandler();  
  215.         }  
  216.         if (handler instanceof CorsConfigurationSource) {  
  217.             return ((CorsConfigurationSource) handler).getCorsConfiguration(request);  
  218.         }  
  219.         return null;  
  220.     }  
  221.     protected HandlerExecutionChain getCorsHandlerExecutionChain(HttpServletRequest request,  
  222.             HandlerExecutionChain chain, CorsConfiguration config) {  
  223.         if (CorsUtils.isPreFlightRequest(request)) {  
  224.             HandlerInterceptor[] interceptors = chain.getInterceptors();  
  225.             chain = new HandlerExecutionChain(new PreFlightHandler(config), interceptors);  
  226.         }  
  227.         else {  
  228.             chain.addInterceptor(new CorsInterceptor(config));  
  229.         }  
  230.         return chain;  
  231.     }  
  232.   
  233.   
  234.     private class PreFlightHandler implements HttpRequestHandler {  
  235.         private final CorsConfiguration config;  
  236.         public PreFlightHandler(CorsConfiguration config) {  
  237.             this.config = config;  
  238.         }  
  239.         @Override  
  240.         public void handleRequest(HttpServletRequest request, HttpServletResponse response)  
  241.                 throws IOException {  
  242.             corsProcessor.processRequest(this.config, request, response);  
  243.         }  
  244.     }  
  245.   
  246.     private class CorsInterceptor extends HandlerInterceptorAdapter {  
  247.   
  248.         private final CorsConfiguration config;  
  249.         public CorsInterceptor(CorsConfiguration config) {  
  250.             this.config = config;  
  251.         }  
  252.         @Override  
  253.         public boolean preHandle(HttpServletRequest request, HttpServletResponse response,  
  254.                 Object handler) throws Exception {  
  255.             return corsProcessor.processRequest(this.config, request, response);  
  256.         }  
  257.     }  
  258.   
  259. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值