SpringBoot学习笔记(二) --- SpringBoot整合Thymeleaf访问HTML页面(idea+gradle)
1.构建一个新的SpringBoot项目,选择依赖为Thymeleaf和web
工具:idea 2019.1
gradle: 5.2.1
SpringBoot 2.1.4
2. 查看引入的依赖正常,查看项目结构
在src文件夹下,除了application.properties文件之外还有两个文件夹 static和templates。static一般用于存放静态资源文件,比如.css文件,.js文件,img文件等,templates文件夹用于存放模板文件,也就是HTML文件等的。application.properties必须存放在src的根目录下面。
3. 在application.properties文件中,写入Thymeleaf的属性
#可以选择换一个端口号启动
server.port=9000
#设置编码为UTF-8
spring.thymeleaf.encoding=UTF-8
#设置支持HTML,如果写成HTML5的话,这个属性校验比较严格
spring.thymeleaf.mode=LEGACYHTML5
#设置前缀
spring.thymeleaf.prefix=classpath:/templates/
#设置后缀
spring.thymeleaf.suffix=.html
#默认缓存是开启的,我们需要将它关闭
spring.thymeleaf.cache=false
4.往template文件中新增一个index.html文件
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo2</title>
</head>
<body>
<h1>这是HTML页面</h1>
<input type="button" id="btn" value="点我">
</body>
</html>
5.在启动类的同级目录中新增一个controller包,以及一个controller类
UserController.java
package com.example.springbootdemo2.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class UserController {
@RequestMapping("/")
public String page(){
return "index";
}
}
在启动类中的@SpringBootApplication注解中,是有一个@ComponentScan注解,扫描的是与他同级的包内部的文件,所以他必须在根目录下,之后新建的,需要被 扫描到的都需要在他的同级或者之下
6. 运行启动类,访问页面测试
访问HTML页面正常。当时将Thymeleaf属性中的后缀改为.jsp,然后去访问JSP页面的话,不会成功,他会将JSP页面当成HTML页面进行显示,也就是JSP页面的第一行当成普通字符串输出打印到浏览器上
7.引入static文件中的静态资源
一般开发,我们会把CSS文件和JS文件放到static文件夹中,那怎么音这些文件到HTML文件中呢?
8. 在static文件夹下新建一个css文件夹,新增一个index.css,一个js文件夹,新增一个index.js文件
index.css 也就给那个按钮增加了一个背景颜色和宽高
#btn {
width: 200px;
height: 100px;
background-color: deeppink;
}
index.js 给按钮增加了一个点击事件
window.onload = function (ev) {
document.getElementById("btn").onclick = function() {
alert("我是js页面");
};
}
9. 一般情况下的引入方式
一般情况的引入方式是,绝对路径或者相对路径
10.运行启动类测试
运行启动类之后,HTML页面并没有把CSS文件和JS文件加载进来,报了两个404,
11.直接使用idea直接使用浏览器打开
使用直接打开浏览器的方式,打开这个页面之后显示成功了,说明我们的路径没有问题。
12. 使用Thymeleaf自带的库来引入
运行结果显示
这里就直接引入了,Thymeleaf自己的一个库,使用这个库的几个标签属性来引入CSS文件。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>demo2</title>
<link th:href="@{css/index.css}" rel="stylesheet">
<script th:src="@{js/index.js}" type="text/javascript"></script>
</head>
<body>
<h1>这是HTML页面</h1>
<input type="button" id="btn" value="点我">
</body>
</html>
Thymeleaf自己的标签属性,还有很多,比如绑定数据,条件,循环等。th:for,th:if, th:text等
另外
我觉得Thymeleaf在HTML页面中的角色和JSTL在jsp页面中的角色功能差不多,也是可以输出后台存在model之中的数据的。