Spring工具 - AntPathMatcher&UrlPathHelper(针对URL进行处理)

本文深入探讨了Spring Boot环境中CORS配置的实现原理,详细解析了UrlBasedCorsConfigurationSource类如何利用AntPathMatcher和UrlPathHelper进行URL匹配与处理。通过分析,读者将了解如何为特定URL设置CORS策略,掌握URL路径的获取与Ant表达式的匹配规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring工具篇(1)- AntPathMatcher&&UrlPathHelper(针对URL进行处理)

JAVA && Spring && SpringBoot2.x — 学习目录

源码版本:SpringBoot2.1.3 内含 Spring-5.1.5
源码位置:org.springframework.web.cors.UrlBasedCorsConfigurationSource#getCorsConfiguration

public class UrlBasedCorsConfigurationSource implements CorsConfigurationSource {
    //使用LinkedHashMap,保证url的顺序
    private final Map<String, CorsConfiguration> corsConfigurations = new LinkedHashMap<>();

    private PathMatcher pathMatcher = new AntPathMatcher();

    private UrlPathHelper urlPathHelper = new UrlPathHelper();
    //方法
    @Override
    @Nullable
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        //获取URL的请求路径
        String lookupPath = this.urlPathHelper.getLookupPathForRequest(request);
        for (Map.Entry<String, CorsConfiguration> entry : this.corsConfigurations.entrySet()) {
            //进行Ant表达式匹配
            if (this.pathMatcher.match(entry.getKey(), lookupPath)) {
                return entry.getValue();
            }
        }
        return null;
    }
}

这个类的是CorsFilter的配置类,我们可以为每一个URL单独的提供CORS的配置。当请求时,根据Ant表达式选择最符合的配置。需要解决的问题:

  1. 如何获取Path路径;
  2. 如何使用Ant表达式进行匹配;

在Spring中提供了UrlPathHelperAntPathMatcher工具类对URL进行匹配以及处理。

1. UrlPathHelper类

源码位置:org.springframework.web.util.UrlPathHelper

UrlPathHelper API官方文档

该类位于Spring web包下,若是基于Spring web开发的应用,可以使用该帮助类里面的方法。

该类是一个帮助类,用于UrlPath的获取。实际上,我们获取请求中的URL是通过Request对象的getContextPath、getServletPath、getRequestURI方法。

在SpringBoot2.x环境下:

  1. 修改web application的上下文路径。
server:
  # 端口号
  port: 8082
  servlet:
    # 应用上下文路径
    context-path: /a
  1. 修改dispatchServlet(servlet-path)的映射路径
    @Bean
    public ServletRegistrationBean dispatcherRegistration(DispatcherServlet dispatcherServlet) {
        return new ServletRegistrationBean(dispatcherServlet,"/api/*");
    }

若请求路径:http://localhost:8082/a/api/test/testool

方法作用结果
request.getContextPath()web application路径/a
getServletPath()servlet的mapping路径/api
getRequestURI()url去除协议域名端口号后的路径/a/api/testool

UrlPathHelper中同时也含有获取request路径的方法:

方法名作用结果
getContextPath获取web application路径/a
getPathWithinApplication获取web application内的路径/api/testool
getServletPath获取servlet-mapping路径/api
getPathWithinServletMapping获取Servlet-mapping映射内的路径/testool
getLookupPathForRequest根据alwaysUseFullPath属性,获取getPathWithinApplication或者getPathWithinServletMapping路径1.alwaysUseFullPath=true/api/testool;2. 否则/testool
getRequestUri获取请求的uri地址/a/api/testool
getOriginatingRequestUri获取转发请求的源地址,若无转发地址,即为本身/a/api/testool

注:若是servlet-mapping=/,则为默认的Servlet容器,此时的ServletPath为uri - contextPath。

一般而言,是调用getLookupPathForRequest方法,获取用户上送地址。

2. AntPathMatcher类

2.1 match方法(url匹配)

我们在UrlPathHelper可以获取到请求地址,而后我们可以对URLs字符串进行匹配。

SpringMVC的路径匹配规则使用Ant规则,其基本规则如下:

  1. ? 匹配一个字符;
  2. * 匹配0个或多个字符;
  3. ** 匹配0个多多个目录;

使用方法:

    @RequestMapping("antPath")
    public void getPath(HttpServletRequest request){
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        String path = urlPathHelper.getLookupPathForRequest(request);
        System.out.println("path路径:"+path);
        AntPathMatcher matcher=new AntPathMatcher();
        boolean match = matcher.match("/**", path);
        System.out.println("是否匹配:"+match);
    }

2.2 combine(url的合并)

[科目版嗯]用于含有Ant路径的合并。

1. 规则如下表所示:

模式1模式2结果
nullnullnull
/hotelsnull/hotels
null/hotels/hotels
/hotels/bookings/hotels/bookings
/hotelsbookings/hotels/bookings
/hotels/*/bookings/hotels/bookings
/hotels/**/bookings/hotels/**/bookings
/hotels{hotel}/hotels/{hotel}
/hotels/*{hotel}/hotels/{hotel}
/hotels/**{hotel}/hotels/**/{hotel}
/*.html/hotels.html/hotels.html
/*.html/hotels/hotels.html
/*.html/*.txtIllegalArgumentException

2. 使用方式:

 /* @param pattern1 the first pattern 模式1
     * @param pattern2 the second pattern 模式2
     * @return the combination of the two patterns 返回结果
     * @throws IllegalArgumentException if the two patterns cannot be combined 两个模式无法合并
     */
    @Override
    public String combine(String pattern1, String pattern2) {
     }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值