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>

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

matthew_leung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值