首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何应用Spring 5引入的PathPatternParser?

如何应用Spring 5引入的PathPatternParser?
EN

Stack Overflow用户
提问于 2019-04-01 14:10:52
回答 2查看 16.3K关注 0票数 8

我想要创建一个以文件路径作为路径变量的GET请求。

正如Spring文档找到的这里中所描述的那样,这应该可以通过以下方式实现: /resources/{*path}。

我使用SpringBoot2.1.2,它使用Spring 5。

但是,当我像这样设置控制器方法时,请求与路由不匹配。一个预期的匹配路径将是例如/resources/some/filepath,它将导致PathVariable " path“为/some/filepath。

代码语言:javascript
复制
  @GetMapping("/resources/{*path}")
  public String content(@PathVariable String path) {
    return null;
  }

我没有找到任何关于使用新PathPattern所需的配置的信息。我发现的关于这个新特性的另一条信息是Baeldung (https://www.baeldung.com/spring-5-mvc-url-matching)上的一篇文章,它没有提到任何配置。所以我希望它能从盒子里出来,但它不管用。

我克隆了“白龙邮报”中提到的项目。相应的单元测试将运行。当我将Controller方法和单元测试复制到我的项目时,它会失败。所以我希望它与配置有关。

谢谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-23 19:31:44

在Spring文档中的spring.mvc.pathmatch.matching-strategy,中,有一个名为常用应用特性的属性,用于“根据注册映射匹配请求路径的策略选择”。

默认值(到目前为止)是ant-path-matcher,,由于您希望使用PathPattern,因此需要将其写入application.properties文件中:

spring.mvc.pathmatch.matching-strategy=path-pattern-parser

票数 7
EN

Stack Overflow用户

发布于 2019-04-11 12:41:06

我终于找到了问题的原因。

多亏了法比安的链接

AntPathMatcher是PathMatcher的默认实现。1.10.12。路径匹配展示了如何配置PathMatcher。但是,PathMatchConfigurer::setPathMatcher使用一个PathMatcher作为参数,而AntPathMatcher是PathMatcher的唯一实现,因此您不能在那里设置PathPattern .

代码语言:javascript
复制
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
            .setUseSuffixPatternMatch(true)
            .setUseTrailingSlashMatch(false)
            .setUseRegisteredSuffixPatternMatch(true)
            .setPathMatcher(antPathMatcher())
            .setUrlPathHelper(urlPathHelper())
            .addPathPrefix("/api",
                    HandlerTypePredicate.forAnnotation(RestController.class));
    }

    @Bean
    public UrlPathHelper urlPathHelper() {
        //...
    }

    @Bean
    public PathMatcher antPathMatcher() {
        //...
    }

}

我在Baeldung项目中找到PathPattern的唯一类是以下类:

代码语言:javascript
复制
@Configuration
public class CorsWebFilterConfig {

    @Bean
    CorsWebFilter corsWebFilter() {
        CorsConfiguration corsConfig = new CorsConfiguration();
        corsConfig.setAllowedOrigins(Arrays.asList("http://allowed-origin.com"));
        corsConfig.setMaxAge(8000L);
        corsConfig.addAllowedMethod("PUT");
        corsConfig.addAllowedHeader("Baeldung-Allowed");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", corsConfig);

        return new CorsWebFilter(source);
    }

}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55457184

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档