spring boot 使用静态资源

./ 当前目录
../ 父级目录
/ 根目录

spring boot 打包时: 

The default includes are as follows:  默认包括的文件
public/**, resources/**, static/**, templates/**, META-INF/**, *
The default excludes are as follows:
.*, repository/**, build/**, target/**, **/*.jar, **/*.groovy   默认排除的

1:spring boot 访问直接映射到一下目录,支持  图片、js、css 等资源的访问

Static resources can be moved to /public (or /static or /resources or /META-INF/resources)
in the classpath root.

     

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

2:可以在 配置文件中做映射解析,例如在static目录下创建html目录,可以做以下映射,不建议使用。

     

spring.mvc.view.prefix=/html/
spring.mvc.view.suffix=.html

3:配置类做静态资源映射

     

/**
 * 配置静态资源映射
 * @author sam
 * @since 2017/7/16
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //将所有/static/** 访问都映射到classpath:/static/ 目录下
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

 例1:

    1.1 

配置静态资源映射
    /**
     * 配置静态资源映射
     */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            //将所有/static/** 访问都映射到classpath:/static/ 目录下
            registry.addResourceHandler("/public/**").addResourceLocations("classpath:/public/js/");
        }

1.2 创建静态资源

     

访问   :http://localhost:8080/public/public.html

结果:public hello js

例2:根据controller做映射

        后台映射

    @RequestMapping("/public")
    public String test3() {
        return "/public/public.html";
    }

访问:http://localhost:8080/public

结果:public hello js

  

原文地址:https://www.cnblogs.com/liyafei/p/8670293.html