SpringBoot+Thymeleaf静态资源的引入问题

springboot与thymeleaf模板的搭建,在pom文件中需要引入依赖


            org.springframework.boot
            spring-boot-starter-thymeleaf
 

 

 在配置静态资源时,可以使用自己的,也可以使用https://www.webjars.org/中的资源,若使用webjars的资源时需要在pom文件中引入你说需要的静态资源,如下图

        
            org.webjars
            jquery
            3.3.1
        
        
            org.webjars
            bootstrap
            4.0.0
        

 web获取静态资源的路径

//WebMvcAutoConfiguration中获取静态资源的路径
String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(
						registry.addResourceHandler(staticPathPattern)
								.addResourceLocations(getResourceLocations(
										this.resourceProperties.getStaticLocations()))
								.setCachePeriod(getSeconds(cachePeriod))
								.setCacheControl(cacheControl));

 

由于this.resourceProperties.getStaticLocations()得到的是静态资源路径的集合,在mvc在加载静态资源时,会从这四个路径下读取。
String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/", "classpath:/resources/",
			"classpath:/static/", "classpath:/public/" };

因此,静态资源最好放在以上四个路径下。不过也可以在application.properties/yml文件中自己定义路径;如果使用自定义的路径,默认加载路径资源会失效

可以自定义多个放静态资源的路径,中间用“,”隔开,
#spring.resources.static-locations=classpath:/hello/,classpath:/xxxx/。……

Thymeleaf使用

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

1.导入thymeleaf的名称空间

2.语法规则

SpringBoot+Thymeleaf静态资源的引入问题_第1张图片

HTML中配置静态资源时,若使用webjars中的资源,可以使用thymeleaf模板中的语法规则来引入, 如th:href="@{/webjars/bootstrap/4.0.0/css/bootstrap.css}"。详细语法查看https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#arithmetic-operations

若使用自己的资源可以使用thymeleaf模板引入,

th:href="@{/asserts/css/signin.css}"

引入的资源路径千万不要静态资源路径的集合中路径的前缀。错误示范:

th:href="@{/static/asserts/css/signin.css}"

 否则自己的资源会失效。

在springboot2.0版本以前拦截器会默认对静态资源不拦截,但是springboot 2.0 以后拦截器会拦截所有,所以需要重写addInterceptors方法,不管是自己的静态资源还是webjars中的资源,都要放行。

 @Override
            public void addInterceptors(InterceptorRegistry registry) {
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns(
                        "/index.html", "/", "/user/login").excludePathPatterns("/asserts/**","/webjars/**");
            }

由于自己在这个地方踩过坑,所以记录下来!

 

你可能感兴趣的:(springboot)