路径匹配、RestFul接口地址匹配工具AntPathMatcher

file

背景

SpringBoot开发RestFul API接口,如果存在鉴权,可能会存在需要比对当前请求的接口是否允许访问;如后台定义了一个接口,@GetMapping("/user/{id}"),根据用户的id查询用户信息;此时如果用户请求/user/1的时候,是否要放行,我们该如何比对,传统的equals是没有办法满足比对需求的,SpringBoot给我们提供了一个工具类AntPathMatcher,用于路径比对

示例
@Test
public void antPathMatcher() {
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    // path路径是否符合pattern的规范
    boolean match = antPathMatcher.match("/user/*", "/user/a");
    System.out.println(match);
    match = antPathMatcher.match("/user/**", "/user/a/b");
    System.out.println(match);
    match = antPathMatcher.match("/user/{id}", "/user/1");
    System.out.println(match);
    match = antPathMatcher.match("/user/name", "/user/a");
    System.out.println(match);

    boolean pattern = antPathMatcher.isPattern("user/{id}");
    System.out.println(pattern);

    // 匹配是不是以path打头的地址
    boolean matchStart = antPathMatcher.matchStart("/1user/a", "/user");
    System.out.println(matchStart);

    // 对路径进行合并 --> /user/a/b
    String combine = antPathMatcher.combine("/user", "a/b");
    System.out.println(combine);

    // 找出模糊匹配中 通过*或者? 匹配上的那一段配置
    String extractPathWithinPattern = antPathMatcher.extractPathWithinPattern("/user/?", "/user/1");
    System.out.println(extractPathWithinPattern);

    // 找出模糊匹配中 找到匹配上的项 如果匹配规则和要匹配的项规则不一致 会报错
    Map<String, String> extractUriTemplateVariables = antPathMatcher
        .extractUriTemplateVariables("{appName:[\\p{L}\\.]+}-sources-{version:[\\p{N}\\.]+}.jar",
            "demo-sources-1.0.0.jar");
    if (null != extractUriTemplateVariables) {
        Iterator<String> iterator = extractUriTemplateVariables.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            System.out.println("extractUriTemplateVariables:" + extractUriTemplateVariables.get(key));
        }
    }
}

file

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一行Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值