源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

spring boot 静态资源处理方法

  • 时间:2022-05-31 05:49 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:spring boot 静态资源处理方法
spring boot 秉承约定优于配置,spring boot在静态资源的处理上就已经默认做了处理。 [b]1.默认资源映射[/b] 映射”/**”的路径到 /static (或/public、/resources、/META-INF/resources), ”/webjars/** 映射到 classpath:/META-INF/resources/webjars/ [img]http://files.jb51.net/file_images/article/201703/201703161551552.png[/img]
[url=http://www.webjars.org/]http://www.webjars.org/[/url],在pom.xml中jQuery依赖
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>jquery</artifactId>
  <version>1.11.3</version>
</dependency>
[img]http://files.jb51.net/file_images/article/201703/201703161551553.png[/img] 引入成功之后,自动把资源放到classpath://META-INFO/resources/webjars目录下,我们可以通过/webjars/** 来访问
[u]复制代码[/u] 代码如下:
<script type="text/javascript" src="${request.contextPath }/webjars/jquery/1.11.3/jquery.js"></script>
4.webjars资源版本控制 既然引入maven进行版本控制,当有新版本的web资源的时候,当然不希望一个个的去客户端修改资源版本号,我们利用WebJarAssetLocator来处理,首先在pom.xml引入依赖
<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>webjars-locator</artifactId>
</dependency>
然后定义一个controller进行拦截
@Controller
public class WebJarsController {

  private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();

  @ResponseBody
  @RequestMapping("/webjarslocator/{webjar}/**")
  public ResponseEntity<?> locateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
    try {
      String mvcPrefix = "/webjarslocator/" + webjar + "/"; // This prefix must match the mapping path!
      String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
      String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
      return new ResponseEntity<>(new ClassPathResource(fullPath), HttpStatus.OK);
    } catch (Exception e) {
      return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
  }
}

在页面上,就这么调用,不需要写具体版本号
[u]复制代码[/u] 代码如下:
<script type="text/javascript" src="${request.contextPath }/webjarslocator/jquery/jquery.js"></script>
5.使用ResourceUrlProvider对自定义的静态资源进行管理 在使用第三方库,我们可以是使用WebJarAssetLocator的方式进行版本管理,但是使用自己写css和js,建议使用ResourceUrlProvider进行版本管理,并避免在版本发生改变时,由于浏览器缓存而产生资源版本未改变的错误 首先我们定义一个controller将路径信息推到前端
@ControllerAdvice
public class ResourceUrlProviderController {

  @Autowired
  private ResourceUrlProvider resourceUrlProvider;

  @ModelAttribute("urls")
  public ResourceUrlProvider urls() {
    return this.resourceUrlProvider;
  }

}

前端页面上,我们这么引入
[u]复制代码[/u] 代码如下:
<script type="text/javascript" src="${request.contextPath }/${urls.getForLookupPath('/js/index.js')}"></script>
而实际上,在生成的html页面上,已加上md5的后缀
[u]复制代码[/u] 代码如下:
<script type="text/javascript" src="/demo//js/index-a789359d91ae435bc45489c5e6978b34.js"></script>
由于ResourceUrlProvider监听了ApplicationListener<ContextRefreshedEvent> 所以在项目refresh的时候,在产生一个新的md5,这样客户端的资源路径就发生改变,回去服务器重新获取。 这就是spring boot的静态资源处理 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部