springboot2.2.x整合thymeleaf无法引用静态资源

springboot2.x整合thymeleaf的教程请看:传送门

首先看一下我的静态资源路径。

 

我们利用jq作为举例,旧的版本使用的方案是

<script type="text/javascript" th:src="@{/js/jquery.js}"></script>

如果没有成功,我们参考网上的教程,书写一个配置类。如:

package com.shegnxi.krw.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author yan
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport{

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        super.addResourceHandlers(registry);
    }

}

这样会有一个问题,那就是yml这些配置文件的自动装配将会失效。这个可以改成实现WebMvcConfigurer接口,区别会写另外一篇文章描述。

如果无效,可以利用自动装配。

mvc:
    static-path-pattern: /static/**
  resources:
    static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
    add-mappings: false

但是这些其实我们是将默认配置的东西给强制要求一遍。

经过debug,我发现是因为2.2.x系列的文件路径是到/resources/的。所以我只需要将引用路径补全即可。

<script type="text/javascript" th:src="@{/static/js/jquery.js}"></script>

完成,这样静态资源就成功了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章