SpringBoot入门(6)—— 自定义访问静态资源

1.SpringBoot 默认访问静态资源路径

默认配置的 /** 映射到 /static (或/public、/resources、/META-INF/resources)

如图:
这里写图片描述
提示:如果启动时未输出上图日志,请关闭拦截器

如下图的资源部署
这里写图片描述
访问 http://localhost:8080/wss.jpg 地址,系统会怎样查找图片呢?
答案:访问默认资源路径:META-INF/resources > resources > static > public

2.自定义访问资源路径
  • 如上图添加 mystatic 文件夹,其中保存文件 wolf.jpg
  • 实现类继承 WebMvcConfigurationSupport 并重写方法 addResourceHandlers
package com.example.demo;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
/**
 * 添加自定义拦截器
 * @author LENOVO
 *
 */
@Configuration
public class MyAppConfig extends WebMvcConfigurationSupport{

    /*@Override
    protected void addInterceptors(InterceptorRegistry registry) {
        //注册自定义拦截器并且添加拦截路径
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/api/*");
        super.addInterceptors(registry);
    }*/

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/mystatic/**").addResourceLocations("classpath:/mystatic/");
        super.addResourceHandlers(registry);
    }
}

通过 http://localhost:8080/mystatic/wolf.jpg 就可以访问自定义静态资源
完!

猜你喜欢

转载自blog.csdn.net/qq_17639593/article/details/80517482