欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot 静态资源访问配置

程序员文章站 2022-03-18 18:04:39
...

静态资源位置

SpringBoot 静态资源访问配置
项目\src\main\resources\static\html\index.html

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>SpringBoot 静态资源访问配置</title>
</head>
<body>
    <p><a href="http://127.0.0.1:8080/static/js/main.js">main.js</a></p>
    <p><a href="http://127.0.0.1:8080/static/css/main.css"/>main.css</body></p>
    <p><a href="http://127.0.0.1:8080/static/images/Ralf.gif"/>Ralf.gif</html></p>
</body>
</html>

配置

推荐方案

项目\src\main\java\com\jerry\configuration\WebConfig.java

package com.jerry.configuration;

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 WebConfig implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

老方案

WebMvcConfigurerAdapter 在 spring 5.0 已经不再推荐

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry){
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

参考资料

SpringMVC的静态资源配置可以参考此篇SSM框架整合 Spring + SpringMVC + Mybatis

相关标签: 静态资源