SpringBoot对WEB项目的静态资源设定了新的路径映射,博主分享一下springboot的静态资源映射问题。
博主使用的IDE是IDEA,创建项目使用的是
项目初始化工具。
JDK版本是1.8
springboot版本是2.4.0
http://127.0.0.1:8080/css/layui.css
使用上面的路径访问静态资源文件,结果直接跳转到错误页面。
查询资料之后,发现使用的springboot版本需要自己手动添加资源映射
package com.liusu.path.config;
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 StaticResourceConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/*").addResourceLocations("classpath:/static/");
}
}
注意
1、配置类需要放在启动类所在的子包下
2、名称自己决定即可,不要忘记加上@Configuration注解
3、不要忘记重启之后再访问
4、博主的是2.4.0版本,不过2.0以上的版本应该都适用