SpringBoot配置静态资源访问位置(类路径下或本地磁盘)
SpringBoot默认静态资源位置可自己参见自动配置原理,自定义方式参见下面。一、配置类路径下面静态资源访问位置1、properties配置文件方式spring.mvc.static-path-pattern=/static/images/**spring.resources.static-locations=classpath:/static/images2、java代码方式import or
SpringBoot默认静态资源位置可自己参见自动配置原理,自定义方式参见下面。
一、配置类路径下面静态资源访问位置
1、properties配置文件方式
spring.mvc.static-path-pattern=/static/images/**
spring.resources.static-locations=classpath:/static/images
2、java代码方式
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 静态资源映射
*/
@Component
public class MyWebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/images/**")
.addResourceLocations("classpath:/static/images/");
}
}
二、配置本地磁盘静态资源访问位置
1、properties配置文件方式
spring.mvc.static-path-pattern=/upload/**
spring.resources.static-locations=file:E:/springbootimg/upload/
注意一定要加file:
2、java代码方式
package com.dl.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class StaticResourcesConfig implements WebMvcConfigurer {
@Value("${filepath.upload}")
private String filepath_upload;
@Value("${filepath.staticAccessPath}")
private String staticAccessPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(staticAccessPath)
.addResourceLocations("file:"+filepath_upload);
}
}
配置文件中的两个位置配置:
filepath.upload = E:/springbootimg/upload/
filepath.staticAccessPath=/upload/**
spring.resources.static-location参数指定了Spring Boot-web项目中静态文件存放地址,该参数默认设置为:classpath:/static,classpath:/public,classpath:/resources,classpath:/META-INF/resources,servlet context:/,可以发现这些地址中并没有/templates这个地址。当配置文件中配置此项后,默认配置失效,使用自定义设置。这里涉及到两个概念:
(1)classpath: 通俗来讲classpath对应的项目中:web-practice\src\main\resources 文件目录。如:“classpath: templates/” 即是将resources目录下的templates文件夹设置为静态文件目录。更深一步讲classpath路径为:文件编译后在target/classes目录下的文件。
(2) 静态文件目录:通俗理解为存放包括 :.html;.jsp;CSS;js;图片;文本文件等类型文件的目录。这些文件都可以通过浏览器url进行访问。同时controller中转发的文件目录也必须被设置为静态文件目录,这就是增加了该参数以后就可以正常访问的原因。
更多推荐

所有评论(0)