spring boot实现静态资源文件自动添加版本号-MD5方式

本文详述了如何通过MD5策略优化Web开发中的静态资源管理,包括配置spring资源链、创建资源URL提供者及在页面中使用,实现资源更新时避免浏览器缓存问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        在我们做Web开发时,免不了与静态资源(css,js,images)打交道,通常的做法是在请求的URL上添加版本信息,这样可以很好的利用客户端缓存机制,只有当资源内容改变时,才需要从服务器重新请求,并加载最新版本资源,本文章介绍MD5方式。

         使用这种方式,当我们文件修改后,手工修改版本号来达到URL文件不被浏览器缓存的目的。

第一步:修改 application.properties 配置文件

spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**

 

第二步:创建 ResourceUrlProviderController 文件
 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.resource.ResourceUrlProvider;
 
/**
 * 静态资源js配置
 * 
 * @author Administrator
 *
 */
@ControllerAdvice
public class ResourceUrlProviderController {
    @Autowired
    ResourceUrlProvider resourceUrlProvider;
 
    @ModelAttribute("urls")
    public ResourceUrlProvider urls() {
        return this.resourceUrlProvider;
    }
}

 第三步:在页面中进行使用:

<script src="${request.contextPath}${urls.getForLookupPath('/static/pl/createCustomTask/list.js')}"></script>

    如果使用的thymeleaf模板引擎的话,那么需要这么进行编写:

<scripttype="text/javascript"th:src="${urls.getForLookupPath('/js/list.js') }"></script>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值