温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot+thymeleaf静态资源引入的方法

发布时间:2022-03-03 15:39:56 来源:亿速云 阅读:416 作者:iii 栏目:web开发

本文小编为大家详细介绍“SpringBoot+thymeleaf静态资源引入的方法”,内容详细,步骤清晰,细节处理妥当,希望这篇“SpringBoot+thymeleaf静态资源引入的方法”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。

  一、静态资源的映射规则

  1.对哪些目录映射?

  classpath:/META-INF/resources/

  classpath:/resources/

  classpath:/static/

  classpath:/public/

  /:当前项目的根路径

  意思是:我们在上面的五个目录下放静态资源文件(比如:jq.js等),可以直接访问(类似以前web项目的webapp下,放到其他目录无法被访问。

  2.为什是这几个目录呢?

  2.1看源码就知道

  SpringBoot自动配置的WebMvcAutoConfirarution.java类:

  @Override

  public void addResourceHandlers(ResourceHandlerRegistry registry) {

  if (!this.resourceProperties.isAddMappings()) {

  logger.debug("Default resource handling disabled");

  return;

  }

  Duration cachePeriod=this.resourceProperties.getCache().getPeriod();

  CacheControl cacheControl=this.resourceProperties.getCache()

  .getCachecontrol().toHttpCacheControl();

  if (!registry.hasMappingForPattern("/webjars/**")) {

  customizeResourceHandlerRegistration(registry

  .addResourceHandler("/webjars/**")

  .addResourceLocations("classpath:/META-INF/resources/webjars/")

  .setCachePeriod(getSeconds(cachePeriod))

  .setCacheControl(cacheControl));

  }

  String staticPathPattern=this.mvcProperties.getStaticPathPattern();

  if (!registry.hasMappingForPattern(staticPathPattern)) {

  customizeResourceHandlerRegistration(

  registry.addResourceHandler(staticPathPattern)

  .addResourceLocations(getResourceLocations(

  this.resourceProperties.getStaticLocations()))

  .setCachePeriod(getSeconds(cachePeriod))

  .setCacheControl(cacheControl));

  }

  }

  ResourceProperties

  @ConfigurationProperties(prefix="spring.resources", ignoreUnknownFields=false)

  public class ResourceProperties {

  //我们可以看到静态资源的映射路径

  private static final String[] CLASSPATH_RESOURCE_LOCATIONS={

  "classpath:/META-INF/resources/", "classpath:/resources/",

  "classpath:/static/", "classpath:/public/" };

  ...

  }

  总的来说:

  WebMvcAutoConfiguration类自动为我们注册了如下目录为静态资源目录,也就是说直接可访问到资源的目录。

  classpath:/META-INF/resources/

  classpath:/resources/

  classpath:/static/

  classpath:/public/

  /:当前项目的根路径

  优先级从上到下。

  所以,如果static里面有个index.html,public下面也有个index.html,则优先会加载static下面的index.html,因为优先级!

读到这里,这篇“SpringBoot+thymeleaf静态资源引入的方法”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI