如何使用SpringBoot访问静态资源

简介

在SpringBoot项目中,静态资源是指不需要通过Web服务器处理的资源,如CSS、JavaScript、图片等,访问静态资源的方法有很多,本文将介绍如何使用SpringBoot内置的静态资源处理器来访问静态资源。

配置文件

在SpringBoot项目中,我们需要在application.propertiesapplication.yml配置文件中进行一些配置,以便让SpringBoot能够正确地访问静态资源。

如何使用SpringBoot访问静态资源

1、配置静态资源路径

application.properties文件中,添加以下配置:

spring.resources.static-locations=classpath:/static/,file:/data/static/

或者在application.yml文件中,添加以下配置:

spring:
  resources:
    static-locations: classpath:/static/, file:/data/static/

这里我们将静态资源分为两部分:classpath:/static/file:/data/static/,前者表示类路径下的静态资源,后者表示文件系统的静态资源,你可以根据实际情况调整这些路径。

2、配置默认缓存策略

application.properties文件中,添加以下配置:

如何使用SpringBoot访问静态资源

spring.resources.cache.period=3600s
spring.resources.cache.control.max-age=86400s

或者在application.yml文件中,添加以下配置:

spring:
  resources:
    cache:
      period: 3600s
      control:
        max-age: 86400s

这里我们设置了静态资源的缓存周期为3600秒(1小时),并设置了最大缓存时间为86400秒(1天),你可以根据实际情况调整这些值。

3、配置编码过滤器

为了确保浏览器能够正确解析中文字符,我们需要配置一个编码过滤器,在application.properties文件中,添加以下配置:

spring.resources.add-encoding-filter=true

或者在application.yml文件中,添加以下配置:

spring:
  resources:
    add-encoding-filter: true

这样,SpringBoot就会自动为所有请求添加一个编码过滤器,确保中文字符能够正确显示。

如何使用SpringBoot访问静态资源

访问静态资源的方法

在SpringBoot项目中,我们可以使用以下方法来访问静态资源:

1、直接通过URL访问:http://localhost:8080/static/css/style.css(假设我们的静态资源放在了类路径下的/static/css/style.css)

2、在HTML模板中引用:<link rel="stylesheet" href="/static/css/style.css">(假设我们的静态资源放在了类路径下的/static/css/style.css)

相关问题与解答

1、如何自定义静态资源的存储路径?

答:在SpringBoot项目中,我们可以通过修改配置文件中的spring.resources.static-locations属性来自定义静态资源的存储路径,如果你想将静态资源放在项目的根目录下,可以将配置修改为:

spring.resources.static-locations=classpath:/,file:/data/custom_static/,file:${user.dir}/custom_static/

原创文章,作者:酷盾叔,如若转载,请注明出处:https://www.kdun.com/ask/111585.html

(0)
酷盾叔订阅
上一篇 2023-12-24 04:55
下一篇 2023-12-24 05:02

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入