我想要创建一个以文件路径作为路径变量的GET请求。
正如Spring文档找到的这里中所描述的那样,这应该可以通过以下方式实现: /resources/{*path}。
我使用SpringBoot2.1.2,它使用Spring 5。
但是,当我像这样设置控制器方法时,请求与路由不匹配。一个预期的匹配路径将是例如/resources/some/filepath,它将导致PathVariable " path“为/some/filepath。
@GetMapping("/resources/{*path}")
public String content(@PathVariable String path) {
return null;
}我没有找到任何关于使用新PathPattern所需的配置的信息。我发现的关于这个新特性的另一条信息是Baeldung (https://www.baeldung.com/spring-5-mvc-url-matching)上的一篇文章,它没有提到任何配置。所以我希望它能从盒子里出来,但它不管用。
我克隆了“白龙邮报”中提到的项目。相应的单元测试将运行。当我将Controller方法和单元测试复制到我的项目时,它会失败。所以我希望它与配置有关。
谢谢你的帮助。
发布于 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
发布于 2019-04-11 12:41:06
我终于找到了问题的原因。
多亏了法比安的链接。
AntPathMatcher是PathMatcher的默认实现。1.10.12。路径匹配展示了如何配置PathMatcher。但是,PathMatchConfigurer::setPathMatcher使用一个PathMatcher作为参数,而AntPathMatcher是PathMatcher的唯一实现,因此您不能在那里设置PathPattern .
@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的唯一类是以下类:
@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);
}
}https://stackoverflow.com/questions/55457184
复制相似问题