美文网首页
SpringBoot下静态资源处理

SpringBoot下静态资源处理

作者: a乐乐_1234 | 来源:发表于2018-10-05 17:30 被阅读0次

    默认情况下,SpringBoot从clsspath下的/META-INF/resources/,/resources/,/static/, /public/或ServletContext根路径下查找静态资源,默认配置变量为ResourceProperties.CLASSPATH_RESOURCE_LOCATIONS。这是通过Spring MVC的ResourceHttpRequestHandler实现的,也可以自定义WebMvcConfigurerAdapter子类覆写addResourceHandlers方法来改变资源映射行为。

    静态资源基本配置

    spring:
      resources:
        static-locations: classpath:/resources/,classpath:/html/ 
      mvc:
        static-path-pattern: /res/**    #静态资源映射路径
    

    经过上面配置后,页面请求的每个静态文件必须包含/res/,这样静态文件才能映射到static-locations路径,没有配置就使用默认的。规范所有静态资源统一前缀,在使用shiro等拦截工具时,可以匹配/res/** 不进行权限检查。

    资源缓存配置

    spring:
      resources:
        cache:
          period:        #间隔周期,默认秒
          cachecontrol:        #缓存控制
            max-age:              #缓存最长时间,默认秒
            no-cache: true      #通过服务器验证后才能重用响应的缓存
            no-store: true        #关闭缓存
    

    资源缓存一般用于缓存应用静态资源和webjars下面的资源,默认情况下,springboot会配置/webjars/**对应classpath:/META-INF/resources/webjars/的资源映射并进行缓存配置,static-path-pattern也会对应static-locations进行缓存配置。

    静态资源访问策略,基于VersionResourceResolver实现

    resources:
        chain:
          gzipped: true    #响应是否进行Gzip压缩处理
          strategy:
            content:        #文件内容MD5 hash
              enabled: true  #是否启用
              paths:        
            fixed:          #固定版本
              enabled: true    #是否启用
              version:
              paths:
    
    1. 文件内容MD5
      如index.css 文件内容当前MD5值是e36d2e05253c6c7085a91522ce43a0b4,后来修改了该文件,产生了新的MD5值g47d2e05253c6c7085a91522ce43a0b4,页面css地址之前是index-e36d2e05253c6c7085a91522ce43a0b4.css,现在必须改成index-g47d2e05253c6c7085a91522ce43a0b4.css才能正确访问该文件,一般这种全局路径前缀,必须在一个地方定义,其他乙方引入,如在freemarker中用全局变量代替,便于全局更改。
    //默认使用FileNameVersionPathStrategy,如path/foo-{version}.css
    public String getResourceVersion(Resource resource) {
            try {
                byte[] content = FileCopyUtils.copyToByteArray(resource.getInputStream());
                return DigestUtils.md5DigestAsHex(content);
            }
            catch (IOException ex) {
                throw new IllegalStateException("Failed to calculate hash for " + resource, ex);
            }
        }
    
    1. 固定版本号
      如:{version}/js/main.js,这个version可以自定义,原理同上。

    相关文章

      网友评论

          本文标题:SpringBoot下静态资源处理

          本文链接:https://www.haomeiwen.com/subject/hlcqaftx.html