最近在做SpringBoot项目的时候遇到了“白页”问题,通过查资料对SpringBoot访问静态资源做了总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
默认路径
在Spring Boot 2.7.2版本中,查看默认静态资源路径,在WebProperties.class
中如下
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
可以看到默认资源路径有4个。
使用Spring Initializr
新建Spring Boot项目,自带static
目录,直接将前端资源文件放到该目录下,启动项目,访问http://localhost:端口号/资源目录/名称.html
即可;
例如,有一个front
目录,该目录下存在一个index.html
文件,将此目录放于src/main/resources/static
下,并且未修改端口号,访问http://localhost:8080/front/index.html
即可看到访问成功。
修改路径
使用配置文件进行修改
对于低版本,在配置文件application.yml
中如下:
spring:
resources:
static-locations: classpath:/
代表将资源目录直接放在src/main/resources/
下
但是,对于高版本,该方式已弃用,不推荐!!!
对于高版本,在配置文件application.yml
中如下:
spring:
web:
resources:
static-locations: classpath:/
高版本这样设置,可以成功访问http://localhost:8080/front/index.html
使用配置类进行修改
新建配置类WebMvcConfig.java
继承WebMvcConfigurationSupport
类
package com.aiw.waimai.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Slf4j
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
/**
* 设置静态资源映射
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始进行静态资源映射。。。");
registry.addResourceHandler("/**").addResourceLocations("classpath:/");
}
}
可以成功访问http://localhost:8080/front/index.html
注意:两种配置方式不可同时存在,并且修改后默认的访问路径就失效了;对于配置类方式,@Slf4j是Lombok提供的注解,方便打印日志,非必须
【更新】网上看到WebMvcConfigurationSupport
已过时,故更新为实现WebMvcConfigurer
接口
package com.aiw.waimai.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 设置静态资源映射
*
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始进行静态资源映射。。。");
registry.addResourceHandler("/**").addResourceLocations("classpath:/");
}
}
到此这篇关于Spring Boot静态资源路径的配置与修改详解的文章就介绍到这了,更多相关Spring Boot静态资源路径内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
本文标题为:Spring Boot静态资源路径的配置与修改详解
- JSP 制作验证码的实例详解 2023-07-30
- 基于Java Agent的premain方式实现方法耗时监控问题 2023-06-17
- Spring Security权限想要细化到按钮实现示例 2023-03-07
- 深入了解Spring的事务传播机制 2023-06-02
- JSP页面间传值问题实例简析 2023-08-03
- Springboot整合minio实现文件服务的教程详解 2022-12-03
- ExecutorService Callable Future多线程返回结果原理解析 2023-06-01
- SpringBoot使用thymeleaf实现一个前端表格方法详解 2023-06-06
- Java实现顺序表的操作详解 2023-05-19
- Java中的日期时间处理及格式化处理 2023-04-18