SpringBoot静态资源文件位置

Stella981
• 阅读 439

SpringBoot可以JAR/WAR的形式启动运行,有时候静态资源的访问是必不可少的,比如:image、js、css 等资源的访问。

一、webjars配置静态路径

实用性不大,简单了解即可。

public class WebMvcAutoConfiguration {
         public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
            } else {
                Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
                CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
                if (!registry.hasMappingForPattern("/webjars/**")) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

                String staticPathPattern = this.mvcProperties.getStaticPathPattern();
                if (!registry.hasMappingForPattern(staticPathPattern)) {
                    this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
                }

            }
        }
}

从代码中可以看出:所有 /webjars/**,都去classpath:/META-INF/resources/webjars/找资源。

webjars提供的依赖官网

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

SpringBoot静态资源文件位置

启动服务,测试访问静态地址:

http://127.0.0.1:9091/hp/webjars/jquery/3.4.1/jquery.js(hp是应用上下文, server.servlet.context-path = /hp)

二、默认静态资源路径

SpringBoot静态资源文件位置 SpringBoot静态资源文件位置

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
            "classpath:/resources/", "classpath:/static/", "classpath:/public/" };

    /**
     * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
     * /resources/, /static/, /public/].
     */
    private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;

    /**
     * Whether to enable default resource handling.
     */
    private boolean addMappings = true;

    private final Chain chain = new Chain();

    private final Cache cache = new Cache();

    public String[] getStaticLocations() {
        return this.staticLocations;
    }

    public void setStaticLocations(String[] staticLocations) {
        this.staticLocations = appendSlashIfNecessary(staticLocations);
    }

    private String[] appendSlashIfNecessary(String[] staticLocations) {
        String[] normalized = new String[staticLocations.length];
        for (int i = 0; i < staticLocations.length; i++) {
            String location = staticLocations[i];
            normalized[i] = location.endsWith("/") ? location : location + "/";
        }
        return normalized;
    }

    public boolean isAddMappings() {
        return this.addMappings;
    }

    public void setAddMappings(boolean addMappings) {
        this.addMappings = addMappings;
    }

    public Chain getChain() {
        return this.chain;
    }

    public Cache getCache() {
        return this.cache;
    }
        ......
        ......
}

View Code

SpringBoot提供了几种默认的资源路径:

classpath:/META-INF/resources/ > classpath:/resources/ > classpath:/static/ > classpath:/public/

备注说明: "/"=>当前项目的根路径

我们在src/main/resources目录下新建 public、resources、static 、META-INF等目录目录,并分别放入 1.jpg 2.jpg 3.jpg 4.jpg 5.jpg 五张图片。

 SpringBoot静态资源文件位置

访问图片地址:http://127.0.0.1:9091/hp/1.jpg,只有5.jpg访问不到。

springboot访问静态资源,默认有两个默认目录:

  • 一个是 src/mian/resource目录(上面将的就是这种情况)
  • 一个是 ServletContext 根目录下( src/main/webapp )

一般来说 src/main/java 里面放Java代码,resource 里面放 配置文件、xml, webapp里面放页面、js之类的。

一般创建的maven项目里面都没有 webapp 文件夹,在这里我们自己在 src/main 目录下创建一个 webapp项目目录。

三、新增静态资源路径

我们在 spring.resources.static-locations后面追加一个配置 classpath:/os/

# 静态文件请求匹配方式
spring.mvc.static-path-pattern=/**
# 修改默认的静态寻址资源目录 多个使用逗号分隔
spring.resources.static-locations = classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/os/

四、设置欢迎界面

源码:

public class WebMvcAutoConfiguration {
            private Optional<Resource> getWelcomePage() {
            String[] locations = getResourceLocations(this.resourceProperties.getStaticLocations());
            return Arrays.stream(locations).map(this::getIndexHtml).filter(this::isReadable).findFirst();
        }

        private Resource getIndexHtml(String location) {
            return this.resourceLoader.getResource(location + "index.html");
        }
}

1. 直接设置静态默认页面

静态资源文件夹下的所有index.html页面,被"/**"映射;

2. 增加控制器的方式

(1) 新增模版引擎的支持

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

(2) 配置核心文件application.properties

server.port=9091
server.servlet.context-path=/hp
spring.mvc.view.prefix=classpath:/templates/

没有设置后缀名。

(3) 设置路由

@Controller
public class IndexController {
    @GetMapping({"/","/index"})
    public String index(){
        return "default";
    }
}

访问http://127.0.0.1:9091/hp/。

3. 设置默认的View跳转页面

(1) 新增模版引擎的支持

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

(2) 配置核心文件application.properties

server.port=9091
server.servlet.context-path=/hp
spring.mvc.view.prefix=classpath:/templates/

(3) 启动文件的修改如下

@SpringBootApplication
public class Demo05BootApplication implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("default");
        registry.addViewController("/index1").setViewName("default");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }

    public static void main(String[] args) {

        SpringApplication.run(Demo05BootApplication.class, args);
    }

}

4. Favicon设置

@Configuration
@ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
public static class FaviconConfiguration implements ResourceLoaderAware {

    private final ResourceProperties resourceProperties;

    private ResourceLoader resourceLoader;

    public FaviconConfiguration(ResourceProperties resourceProperties) {
        this.resourceProperties = resourceProperties;
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @Bean
    public SimpleUrlHandlerMapping faviconHandlerMapping() {
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
        mapping.setUrlMap(Collections.singletonMap("**/favicon.ico", faviconRequestHandler()));
        return mapping;
    }

    @Bean
    public ResourceHttpRequestHandler faviconRequestHandler() {
        ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
        requestHandler.setLocations(resolveFaviconLocations());
        return requestHandler;
    }

    private List<Resource> resolveFaviconLocations() {
        String[] staticLocations = getResourceLocations(this.resourceProperties.getStaticLocations());
        List<Resource> locations = new ArrayList<>(staticLocations.length + 1);
        Arrays.stream(staticLocations).map(this.resourceLoader::getResource).forEach(locations::add);
        locations.add(new ClassPathResource("/"));
        return Collections.unmodifiableList(locations);
    }

}

SpringBoot 默认是开启Favicon,并且提供了一个默认的Favicon,如果想关闭Favicon,只需要在application.properties中添加

spring.mvc.favicon.enabled=false

如果想更改Favicon,只需要将自己的Favicon.ico(文件名不能改动),放置到类路径根目录、类路径META_INF/resources/下、类路径resources/下、类路径static/下或者类路径public/下。

五、WebMvcConfigurer接口

1. WebMvcConfigurerAdapter过时

在Springboot中配置WebMvcConfigurerAdapter的时候发现这个类过时了。所以看了下源码,发现官方在spring5弃用了WebMvcConfigurerAdapter,因为springboot2.0使用的spring5,所以会出现过时。

WebMvcConfigurerAdapter已经过时,在新版本中被废弃,以下是比较常用的重写接口:

/** 解决跨域问题 **/
public void addCorsMappings(CorsRegistry registry) ;
/** 添加拦截器 **/
void addInterceptors(InterceptorRegistry registry);
/** 这里配置视图解析器 **/
void configureViewResolvers(ViewResolverRegistry registry);
/** 配置内容裁决的一些选项 **/
void configureContentNegotiation(ContentNegotiationConfigurer configurer);
/** 视图跳转控制器 **/
void addViewControllers(ViewControllerRegistry registry);
/** 静态资源处理 **/
void addResourceHandlers(ResourceHandlerRegistry registry);
/** 默认静态资源处理器 **/
void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer);

方案1:直接实现WebMvcConfigurer

@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

方案2:直接继承WebMvcConfigurationSupport

@Configuration
public class WebMvcConfg extends WebMvcConfigurationSupport {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/index").setViewName("index");
    }
}

其实,源码下WebMvcConfigurerAdapter是实现WebMvcConfigurer接口,所以直接实现WebMvcConfigurer接口也可以;WebMvcConfigurationSupport与WebMvcConfigurerAdapter、接口WebMvcConfigurer处于同一个目录下WebMvcConfigurationSupport包含WebMvcConfigurer里面的方法,由此看来版本中应该是推荐使用WebMvcConfigurationSupport类的,

WebMvcConfigurationSupport应该是新版本中对WebMvcConfigurerAdapter的替换和扩展。

2. 关于加载目录问题

// 可以直接使用addResourceLocations 指定磁盘绝对路径,同样可以配置多个位置,注意路径写法需要加上file:
registry.addResourceHandler("/myimgs/**").addResourceLocations("file:H:/myimgs/");
// 访问myres根目录下的fengjing.jpg 的URL为 http://localhost:8080/fengjing.jpg (/** 会覆盖系统默认的配置)
registry.addResourceHandler("/**").addResourceLocations("classpath:/myres/").addResourceLocations("classpath:/static/");
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Easter79 Easter79
2年前
SpringBoot静态资源文件位置
SpringBoot可以JAR/WAR的形式启动运行,有时候静态资源的访问是必不可少的,比如:image、js、css等资源的访问。一、webjars配置静态路径实用性不大,简单了解即可。publicclassWebMvcAutoConfiguration{publicvoidaddReso
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这