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>

完成,這樣靜態資源就成功了。

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