SpringMVC源代码学习外传(三)RequestCondition

以下内容基于书:《看透SpringMVC-源代码分析与实践》 
基本照搬。。。用于自己查阅备忘。加上外传关键字的是讨论一些SpringMVC的特定类的使用方法,非外传的是对启动流程/请求处理流程,我们可以看作主线剧情。

RequestCondition是一个springMVC的接口,专门用于保存从request提取出的用于匹配handler的条件。 
它的继承树如下:

RequestCondition继承树

代码如下:

public interface RequestCondition<T> {
    T combine(T other);
    T getMatchingCondition(HttpServletRequest request);
    int compareTo(T other, HttpServletRequest request);
}

可以看到它的抽象实现,AbstractRequestCondition有8个子类,下面介绍下他们

CompositeRequestCondition

它本身不实际做匹配,而是可以存储多个RequestCondition,用的时候遍历它存储的这些RequestCondition进行匹配即可,也就是责任链模式,这种模式在SpringMVC中很常见,类名是CompositeXXX或者XXXComposite的就是。部分代码如下:

private final RequestConditionHolder[] requestConditions;
@Override
public CompositeRequestCondition getMatchingCondition(HttpServletRequest request) {
    if (isEmpty()) {
        return this;
    }
    RequestConditionHolder[] matchingConditions = new RequestConditionHolder[getLength()];
    for (int i = 0; i < getLength(); i++) {
        matchingConditions[i] = this.requestConditions[i].getMatchingCondition(request);
        if (matchingConditions[i] == null) {
            return null;
        }
    }
    return new CompositeRequestCondition(matchingConditions);
}

AbstractRequestCondition的其他子类

每个子类表示一种匹配条件,如,PatternsRequestCondition使用url匹配。 
RequestMethodsRequestCondition使用RequestMethod做匹配。

RequestMappingInfo

我们在介绍AbstractHandlerMethodMapping1时提到它的泛型默认实现是RequestMappingInfo, 
它的内部用七个变量保存了七个RequestCondition,匹配时用他们进行匹配,这也就是@RequestMapping中可以给处理器指定多种匹配方式的原因。

private final PatternsRequestCondition patternsCondition;
private final RequestMethodsRequestCondition methodsCondition;
private final ParamsRequestCondition paramsCondition;
private final HeadersRequestCondition headersCondition;
private final ConsumesRequestCondition consumesCondition;
private final ProducesRequestCondition producesCondition;
private final RequestConditionHolder customConditionHolder;

应用实例

先留空以后写代码测试补上

 

posted @ 2017-08-17 16:58  0101无限的空间  阅读(1268)  评论(0编辑  收藏  举报