说明
前后端分离的项目请绕道,本文只针对springboot + thymeleaf的项目,使用md5策略。
以下两种方法可以同时使用
方法一
写一个全局的@ControllerAdvice控制类
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;
@ControllerAdvice
public class ControllerConfig {
@Autowired
private ResourceUrlProvider resourceUrlProvider;
@ModelAttribute("urls")
public ResourceUrlProvider urls() {
return this.resourceUrlProvider;
}
}
thymeleal引入静态资源文件${urls.getForLookupPath(‘资源文件路径’)}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" th:href="${urls.getForLookupPath('/css/init.css')}">
<script type="text/javascript" src="/webjars/jquery/3.4.1/jquery.js"></script>
<script type="text/javascript">
$(function () {
$('#aa').text('你好');
});
</script>
</head>
<body>
<div th:text="${success}"></div>
<div id="aa"></div>
</body>
</html>
测试代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping(value = "success")
public String success(ModelMap map) {
map.put("success", "成功");
return "success";
}
}
访问http://localhost:8080/success
页面显示
查看网页源代码
方法二 (更简单)
写一个@Configuration配置类,加一个ResourceUrlEncodingFilter ,本人比较懒,直接写在了启动类中。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.resource.ResourceUrlEncodingFilter;
@SpringBootApplication
public class HelloworldMainApplication {
public static void main(String[] args) {
SpringApplication.run(HelloworldMainApplication.class, args);
}
@Bean
public ResourceUrlEncodingFilter resourceUrlEncodingFilter() {
return new ResourceUrlEncodingFilter();
}
}
thymeleal引入静态资源文件@{资源文件路径}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" type="text/css" th:href="@{/css/init.css}">
<script type="text/javascript" src="webjars/jquery/3.4.1/jquery.js"></script>
<script type="text/javascript">
$(function () {
$('#aa').text('欢迎');
});
</script>
</head>
<body>
<div th:text="${success1}"></div>
<div id="aa"></div>
</body>
</html>
测试代码
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping(value = "success1")
public String success1(ModelMap map) {
map.put("success1", "成功");
return "success1";
}
}
访问http://localhost:8080/success1
页面显示
查看网页源代码
完成
普通ssm + jsp项目后期加对静态资源缓存控制的方法请看
记一次项目后期对静态资源的处理