【Spring】addResourceHandlers(ResourceHandlerRegistry registry)中文无法访问

0.问题复现

使用Spring Boot配置映射静态资源目录后,英文和数字可以正常进行访问,但是中文就提示404

1
2
3
4
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/file/video/**").addResourceLocations(props.getVideoFolder());
}

1.解决办法

原文传送门,有分析过程

1.1 UrlPathHelper 设置 UrlDecode 为false

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Configuration
public class WebConfig implements WebMvcConfigurer {

@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper=new UrlPathHelper();
urlPathHelper.setUrlDecode(false);
urlPathHelper.setDefaultEncoding(StandardCharsets.UTF_8.name());
configurer.setUrlPathHelper(urlPathHelper);
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/files/**")
.addResourceLocations("file:E:/FileUpload/HmiInterface/");
}
}

1.2 使用原来的AntPathMatcher (推荐)

1
2
3
4
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher

版本问题,最为致命


【Spring】addResourceHandlers(ResourceHandlerRegistry registry)中文无法访问
https://www.yangxj96.com/Spring/SpringBootAddResourceHandlers/
作者
道一
发布于
2022年12月24日
许可协议