static目录的访问
情景
- 项目中需要做一个模板文件下载的功能,可以采用将文件流写入response,然后返回response这种方式。但本次直接使用的a标签,地址指向目标文件路径,从而实现文件下载。
问题
- 于是需要访问静态文件,springboot中将静态文件放置在resource下的static中,templates用来存放html页面文件。但访问的时候,直接报404。静态文件访问不到。
解决方式
需要加一个拦截器,将对应的请求映射到静态目录中。
@Configuration
@EnableWebMvc
@ComponentScan
public class InterceptorConfiger implements WebMvcConfigurer {
private ApplicationContext applicationContext;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");
registry.addResourceHandler("/templates/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/templates/");
}