Spring源码之AntPathMatcher、PathMatcher(路径匹配器)

概述

部分参考:https://blog.csdn.net/andy_zhang2007/article/details/88884286

今天在阅读Spring源码时发现了AntPathMatcher这个类

我们首先看一下PathMatcher接口(路径匹配器)

package org.springframework.util;

import java.util.Comparator;
import java.util.Map;

public interface PathMatcher {

	/**
	 * <p>
	 *     判断指定的路径 path 是否是一个 pattern(模式)
	 *     如果返回值是 false,也就是说 path 不是一个模式,而是一个静态路径(真正的路径字符串),
	 *     那么就不用调用方法 {@link #match} 了,因为对于静态路径的匹配,直接使用字符串等号比较就足够了。
	 * </p>
	 */
	boolean isPattern(String path);

	/**
	 * <p>根据当前 PathMatcher 的匹配策略,检查指定的径 path 和指定的模式 pattern 是否匹配</p>
	 * @param pattern 用于检测路径字符串是否匹配于某个模式时所用的模式
	 * @param path 需要被检测的路径字符串
	 * @return {@code true} 表示匹配, {@code false} 表示不匹配
	 */
	boolean match(String pattern, String path);

	/**
	 * <p>根据当前 PathMatcher 的匹配策略,检查指定的径 path 和指定的模式 pattern 之间是否为前缀匹配</p>
	 */
	boolean matchStart(String pattern, String path);
	/**
	 * <p>
	 *     给定一个模式 pattern 和一个全路径 path,判断路径中和模式匹配的部分。
	 *     该方法用于发现路径中的哪一部分是和模式能动态匹配上的部分。它会去除路径中开头静态部分,
	 * 	   仅仅返回那部分真正和模式匹配的上的部分。
	 * 	   例子 : "myroot/*.html" 为 pattern , "myroot/myfile.html" 为路径,
	 * 	   则该方法返回 "myfile.html".
	 * 	   具体的检测规则根据当前 PathMatcher 的匹配策略来顶。
	 * </p>
	 */
	String extractPathWithinPattern(String pattern, String path);

	/**
	 * <p>
	 *     给定一个模式和一个路径,提取其中的 URI 模板变量信息。URI模板变量表达式格式为 "{variable}"
	 * 	   例子 : pattern  为 "/hotels/{hotel}" ,路径为 "/hotels/1", 则该方法会返回一个 map ,
	 * 	   内容为 : "hotel"->"1".
	 * </p>
	 */
	Map<String, String> extractUriTemplateVariables(String pattern, String path);
    
	Comparator<String> getPatternComparator(String path);

	/**
	 * <p>合并两个模式。具体合并的算法由实现类决定。</p>
	 */
	String combine(String pattern1, String pattern2);

}

从接口代码来理解概念还是有些抽象,下面我们列举一些基于实现类AntPathMatcher的例子来增强理解 。

AntPathMatcher使用例子

AntPathMatcher antPathMatcher = new AntPathMatcher();

antPathMatcher.isPattern("/user/001");// 返回 false
antPathMatcher.isPattern("/user/*"); // 返回 true
antPathMatcher.match("/user/001","/user/001");// 返回 true
antPathMatcher.match("/user/*","/user/001");// 返回 true
antPathMatcher.matchStart("/user/*","/user/001"); // 返回 true
antPathMatcher.matchStart("/user/*","/user"); // 返回 true
antPathMatcher.matchStart("/user/*","/user001"); // 返回 false
antPathMatcher.extractPathWithinPattern("uc/profile*","uc/profile.html"); // 返回 profile.html
antPathMatcher.combine("uc/*.html","uc/profile.html"); // uc/profile.html


版权声明:本文为kano_2525原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。