springboo2.0 静态资源访问

springboot自动为我们提供了静态资源处理,在2.0之前的版本它会默认去以下几个目录下去找静态资源,我们只要将资源放在下面的目录即可:

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

但是在2.0版本以后,放在classpath:/resources/static以及classpath:/webapp目录下的资源才会被自动识别,这个时候我们的访问路路径是localhost:8080/111.png

springboot2.0提供了配置来指定我们静态资源的位置如下:


spring.mvc.static-path-pattern=/static/**

添加了这个配置springboot默认的资源访问路径就不生效了,放在classpath:/resources/static以及classpath:/webapp目录下的资源访问方式变成了localhost:8080/static/111.png了。

classpath 即WEB-INF下面的classes目录,maven项目中src/main/resource以及src/main/webapp目录的内容都会放到里面,注意要在pom.xml中配置resource资源

访问路径为:http://localhost:8080/static/static/img/2221.png

如果我们要自定义静态文件的访问路径,需要自己通过拦截器来实现:

我们自己定义拦截器类实现WebMvcConfigurer,在旧版的springboot中,一般是继承WebMvcConfigurerAdapter类,但是2.0以后,WebMvcConfigurer接口定义了很多默认的方法,不过需要jdk1.8+,我们可以定义自己的规则如下:

@Component
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //映射一个自定义的访问路径,下面的配置我们可以通过/mypath来访问/static目录下的资源
        registry.addResourceHandler("/mypath/**").addResourceLocations("classpath:/static/");

        //也可以自定义一个本地或者服务器上的路径读取资源
        registry.addResourceHandler("/upload/**").addResourceLocations("file:/Users/pcname/Desktop/");
    }
}

我们也可以通过配置让拦截器排除相关映射路径,配置如下:

    //拦截器忽略拦截某个配置,下面的拦截器是继承了HandlerInterceptorAdapter类,只打印了日志
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new BaseInterceptor()).excludePathPatterns("/mypath/img/**");
    }

另外配置WebMvcConfigurer也可以通过javaBean的方式来配置,参考链接:

javabean配置WebMvcConfigurer

posted @ 2018-12-18 20:28  恒远有多远  阅读(411)  评论(0)    收藏  举报