1.准备工作:
1.1 静态资源的引入:
我们会发现springboot项目下已经不存在WEB-INF目录,那我们的静态资源(html,css,js文件)应放在哪里呢?
1. 通过webjars:
WebJars是将客户端(浏览器)资源(JavaScript,Css等)打成jar包文件,以对资源进行统一依赖管理。WebJars的jar包部署在Maven中央仓库上。可以解决文件混乱、版本不一致等问题。WebJars提供给我们这些前端资源的jar包形式,我们就可以进行依赖管理。
我们从 官网(https://www.webjars.org/)下复制对应的maven依赖。
源码:
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
打开我们导入的资源,发现里面的目录和源码中的一样,意思是我们输入/webjars/**,然后idea会自动找对应文件夹下的资源文件。
例:我们输入http://localhost:8080/webjars/bootstrap/5.0.0-beta3/css/bootstrap.css,打开了css资源文件。
2. 通过静态资源文件夹:
可以看到有三个选择,resources,static,public
直接地址框输入1.js就可以访问到。
1.2 首页的设置:
源码:
private Resource getIndexHtml(Resource location) {
try {
Resource resource = location.createRelative("index.html");
if (resource.exists() && (resource.getURL() != null)) {
return resource;
}
我们将首页名称设置为index.html,放在可访问的资源目录下,springboot会自动跳转到此页面。
1.3 模板引擎:
我们常规的写法应该是从controller中跳转到index页面,但我们发现springboot中缺少视图解析器,所以我们引入 模板引擎 thymeleaf。
模板引擎,顾名思义,是一款模板,模板中可以动态的写入一些参数,我们将这些参数在代码中传入,以保证数据在页面的动态调用,这就是引擎要做的,页面和数据的动态传输模板。
thymeleafProperties.java:源码文件
由此可以看到,SpringBoot若想使用模板引擎,那么需要将html文件放入在指定的文件夹才能被识别,SpringBoot这里默认识别的动态资源文件夹是templates文件夹。 并且它会为我们在controller中返回的字符串后面自动添加.html的后缀。
(templates文件夹就像原来的WEB-INF,只有从controller中跳转才可以访问到)
@Controller
public class helloController {
@RequestMapping("/hello")
public String hello(){
// model.addAttribute("msg","hello springboot");
return "hello";
}
}
//html
<h1>hi</h1>
1.使用thymeleaf:
添加依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
在html页面导入,帮助我们使用thymeleaf。
<html lang="en" xmlns:th="http://www.thymeleaf.org">
通过model向前端传入数据。
@Controller
public class helloController {
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","hello springboot");
return "hello";
}
}
通过thymeleaf接受并展示数据。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>欢迎页面</title>
</head>
<body>
<h1 th:text="${msg}"></h1>
</body>
</html>
2.thymeleaf语法
变量表达式: ${…} --> 取变量的值并输出
选择变量表达式: *{…}
消息表达式: #{…}
链接网址表达式: @{…}
片段表达式: ~{…}
th:text --> 可对表达式或变量求值,并将结果显示在其被包含的 html 标签体内替换原有html文本
th: 任意html属性 -->来替换原生属性的值
输出数集合内内容
model.addAttribute("msgarr", Arrays.asList("KKKK","WWWW"));
<h1 th:each="user:${msgarr}" th:text="${user}"></h1>