Thymeleaf
- Thymeleaf是一款用于渲染XML/XHTML/HTML5内容的模板引擎。类似JSP,Velocity,FreeMaker等,它也可以轻易的与Spring MVC等Web框架进行集成作为Web应用的模板引擎。与其它模板引擎相比,Thymeleaf最大的特点是能够直接在浏览器中打开并正确显示模板页面,而不需要启动整个Web应用。
优点
1、动静结合:Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。
2、开箱即用:它提供标准和spring标准两种方言,可以直接套用模板实现JSTL、 OGNL表达式效果,避免每天套模板、该jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
3、多方言支持:Thymeleaf 提供spring标准方言和一个与 SpringMVC 完美集成的可选模块,可以快速的实现表单绑定、属性编辑器、国际化等功能。
4、与SpringBoot完美整合,SpringBoot提供了Thymeleaf的默认配置,并且为Thymeleaf设置了视图解析器,我们可以像以前操作jsp一样来操作Thymeleaf。
Spring Boot整合Thymeleaf
一、创建Spring Boot项目ThymeleafDemo
二、在全局配置文件里配置thymeleaf属性
#缓存配置,默认即是true,开发阶段设置为false
spring.thymeleaf.cache = false
#设置模板使用的编码为utf-8
spring.thymeleaf.encoding = UTF-8
#指定为模板使用的模式为html5,默认html
spring.thymeleaf.mode = HTML5
#指定前缀,默认位置为/templates/,可以修改成其它位置
spring.thymeleaf.prefix = classpath:/templates/
#指定模板文件后缀,默认值为.html,可以修改成其它值
spring.thymeleaf.suffix = .html
三、创建登录控制器LoginController
- 创建controller子包
package net.lj.lesson09.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.Calendar;
/**
* 登录控制器
*/
@Controller
public class LoginController {
/**
* 通过请求“toLoginPage”跳转到templates目录下的
* login页面,并把当前年份数据保存到模型对象中
*/
@GetMapping("/toLoginPage")
public String toLoginPage(Model model){
model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
return "login"; // 返回逻辑页面视图名称
}
}
四、创建模板文件login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<span th:text="${currentYear}">今年</span> -
<span th:text="${currentYear} + 1">明年</span>
</body>
</html>
启动测试
- 静态访问:直接打开网页
- 动态访问:启动项目
Spring Boot集成Bootstrap
一、引用在线文档
- 在login.HTML文件中
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
<script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
二、引用离线方式
1.下载Bootstrap、并解压缩拖入static目录
链接:https://pan.baidu.com/s/1gAqovmG3EDDRSAm4LfXEcA
提取码:1234
2、编写登录页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
<link th:href="@{/bootstrap/css/bootstrap.css}" rel="stylesheet">
<javascript th:src="@{/bootstrap/js/jquery-3.4.1.min.js}"></javascript>
<javascript th:src="@{/bootstrap/js/bootstrap.bundle.js}"></javascript>
<javascript th:src="@{/bootstrap/js/bootstrap.js}"></javascript>
</head>
<body>
<div class="col-6 m-auto" style="margin-top:30px!important;">
<div class="text-center">
<span th:text="${currentYear}">今年</span> -
<span th:text="${currentYear} + 1">明年</span>
</div>
<div class="border border-info bg-light p-2" style="border-radius: 5px">
<form action="/login" method="post">