Spring Boot 集成 Thymelaf 模板

  • 集成 Jsp 模板
    • 引入依赖 + 配置文件
    • 启动项目
    • 控制器访问 jsp 页面
  • 集成 Thymeleaf 模板
    • 引入依赖 + 配置文件
    • 控制器访问 html 页面
  • Thymeleaf 基本使用
    • 展示单个数据 th:text、th:utext、th:value
    • 展示对象数据
    • 条件展示数据 th:if、运算符
    • 展示多条数据 th:each
    • 引入静态资源
  • 综合案例

SpringBoot 知识点目录: SpringBoot 核心知识点整理!

什么是模板引擎?

集成 Jsp 模板

引入依赖 + 配置文件

引入 jsp 的集成 jar包:

<dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version>
</dependency><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId>
</dependency>

引入 jsp 运行插件:

<build><finalName>springboot_day1</finalName><!--引入jsp运行插件--><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins>
</build>

配置文件 中 配置 视图解析器

spring.mvc.view.prefix=/     # / 代表访问项目中webapp中页面
spring.mvc.view.suffix=.jsp

启动项目

  • 第一种方式:使用插件启动
  • 第二种方式:使用 idea 中指定工作目录启动[推荐]


    通过 http://localhost:8080/index.jsp 可以访问到 默认 的 index.jsp 界面。

控制器访问 jsp 页面

创建一个 /webapp/back/index.jsp 页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
<html>
<body>
<h2>this is Back Directory Hello World!</h2><h1>获取项目名字: ${requestScope.name}   ${name}</h1><c:forEach items="${requestScope.users}" var="user">ID: ${user.id}<br> NAME: ${user.name} <br> AGE: ${user.age} <br> BIR: ${user.bir}<br> --------------------------------------------- <br>
</c:forEach>配置文件中通过 server.servlet.jsp.init-parameters.developmetn=true 开启热部署了
</body>
</html>

写一个控制器:

@Controller // 注意区别, 这里不用 @RestController
@RequestMapping("user")
public class UserController {@GetMapping("findAll")public String findAll(HttpServletRequest request, Model model) {System.out.println("查询所有");model.addAttribute("name", "zhenyu");List<User> users = new ArrayList<>(Arrays.asList(new User("1", "zhenyu", 20, new Date()),new User("2", "chenchen", 23, new Date())));model.addAttribute("users", users);return "back/index"; // 视图解析器: 前缀+逻辑名+后缀 = /back/index// return "index"; 视图解析器: 前缀+逻辑名+后缀 = /index.jsp}
}

访问路径:localhost:8080/user/findAll

集成 Thymeleaf 模板

Thymeleaf 是跟 VelocityFreeMarker 类似的模板引擎,它可以完全替代 JSP,相较与其他的模板引擎相比,Thymeleaf 在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。(jsp 必须运行服务器才能访问)

引入依赖 + 配置文件

<!--使用thymelaf-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

配置文件:

# 使用模板目录
spring.thymeleaf.prefix=classpath:/templates/
# 使用模板后缀
spring.thymeleaf.suffix=.html
# 使用模板编码
spring.thymeleaf.encoding=UTF-8
# 使用模板响应类型
spring.thymeleaf.servlet.content-type=text/html# 默认无法直接访问templates下的页面, 需要设置
# 以后static下放css与js, templates下放页面
spring.resources.static-locations=classpath:/templates, classpath:/static

引入下面的依赖是为了可以直接访问 html 页面:

spring.resources.static-locations=classpath:/templates, classpath:/static

例如 不经过控制器 访问 resources/templates/hello.html:如果不配置上面则无法访问。

http://localhost:8080/index.html

控制器访问 html 页面

使用 Thymeleaf 模板页面 默认放在 resources/templates 目录中

创建一个 /resources/templates/hello.html 页面:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>hello</title>
</head>
<body>SpringBoot 集成 Thymeleaf!!!</body>
</html>

编写控制器:

@Controller
@RequestMapping("/hello")
public class HelloController {@GetMapping("/hello")public String hello() {System.out.println("hello spring boot!");return "hello";}
}

测试访问:

http://localhost:8080/hello/hello

Thymeleaf 基本使用

基本语法包含以下:后面介绍一些常用的,更具体的用到还需要查阅资料。

在页面中使用 Thymeleaf 时必须加入以下命名空间:

<html lang="en" xmlns:th="http://www.thymeleaf.org">

展示单个数据 th:text、th:utext、th:value

控制器中设置数据:

// 控制器中设置数据
model.addAttribute("name", "振宇"); // 或者 request.setAttribute("name", "振宇");
model.addAttribute("username", "<a href=‘’>yusael</a>");
  • 页面中获取原样数据(不解析数据中的 html 标签):
<!-- 页面中获取数据 -->
<span th:text="${name}"/>
  • 获取并解析含有 html 标签 的数据:
<span th:utext="${username}"></span>
  • 将数据赋值给表单元素:
<!-- 将数据赋值给表单元素 -->
<input type="text" th:value="${name}"/>

总结:

  1. 使用 th:text="${属性名}" 获取对应数据,获取数据时会将对应标签中数据清空;
  2. 使用 th:utext="${属性名}" 获取对应的数据,可以将数据中 html 先解析再渲染到页面;
  3. 使用 th:value="${属性名}" 获取数据直接作为表单元素 value 属性

展示对象数据

// 控制器中设置数据
model.addAttribute("user",  new User("1", "振宇", 21, new Date()));
id:   <span th:text="${user.id}"></span>
name:<span th:text="${user.name}"></span>
age: <span th:text="${user.age}"></span>
bir: <span th:text="${user.bir}"></span>  ====日期格式化  <span th:text="${#dates.format(user.bir, 'yyyy-MM-dd HH:mm')}"></span>

条件展示数据 th:if、运算符

// 控制器中设置数据
model.addAttribute("user",  new User("1", "振宇", 21, new Date()));
<span th:if="${user.age} eq 23">青年</span>
<!--年龄小于等于23才会展示名字-->
<span th:if="${user.age} le 23" th:text="${user.name}"></span>

运算符:

  • gt : great than >
  • ge : great equal >=
  • eq : equal ==
  • lt : less than <
  • le : less equal <=
  • ne : not equal !=

展示多条数据 th:each

// 控制器中设置数据
List<User> users = Arrays.asList(new User("2", "张三", 23,  new Date()),new User("3", "李四", 24, new Date())
);
model.addAttribute("users", users);
  • 直接遍历集合:
<ul th:each="user : ${users}"><li th:text="${user.id}"/><li th:text="${user.name}"/><li th:text="${user.age}"/><li th:text="${#dates.format(user.bir, 'yyyy年MM月dd日')}"/>
</ul>
  • 遍历时获取遍历状态:
<ul th:each="user, userStat : ${users}"><li>当前遍历的次数:<span th:text="${userStat.count}"/>当前遍历的索引:<span th:text="${userStat.index}"/>当前遍历是否是奇数行:<span th:text="${userStat.odd}"/>当前遍历是否是偶数行:<span th:text="${userStat.even}"/></li>
</ul>

引入静态资源

使用 Thymeleaf 模板项目中 静态资源 默认放在 resources/static 目录中

项目中放入对应静态资源:

页面中引入:通过 @{/xxx} 去获取 resources/static 路径

<link rel="stylesheet" th:href="@{/css/index.css}">
<script th:src="@{/js/jquery-3.5.0.min.js}"></script>

综合案例

User:

@Data
@AllArgsConstructor
@ToString
public class User {private String id;private String name;private Integer age;private Date bir;
}

UserController:

@Controller
@RequestMapping("user")
public class UserController {@GetMapping("findAll")public String findAll(HttpServletRequest request, Model model) {System.out.println("查询所有");model.addAttribute("name", "振宇");model.addAttribute("username", "<a href=‘’>yusael</a>");model.addAttribute("user", new User("1", "小三", 23, new Date()));List<User> users = Arrays.asList(new User("2", "张三", 23,  new Date()),new User("3", "李四", 24, new Date()));model.addAttribute("users", users);return "index"; // 逻辑名}@GetMapping("delete")@ResponseBody // 以json响应给浏览器public String delete(String id, String name) {return "删除id为:" + id + ", name为:" + name + "的信息。";}
}

resources/templates 目录下 index.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Index</title>
</head><body><h1>this is thymeleaf html</h1><h1>展示单个数据</h1>欢迎: <span th:text="${name}"/>哈哈<br>username: <span th:utext="${username}"></span><br>输入: <input type="text" th:value="${name}"><br><h1>展示对象数据</h1><ul><li>id: <span th:text="${user.id}"/></li><li>name: <span th:text="${user.name}"/></li><li>age: <span th:text="${user.age}"/></li><li>bir: <span th:text="${user.bir}"/> ==== 格式化:<span th:text="${#dates.format(user.bir, 'yyyy-MM-dd')}"/></li></ul><h1>有条件展示数据</h1><!--年龄小于等于23才会展示--><span th:if="${user.age} le 23" th:text="${user.name}"></span><h1>展示多个数据</h1><ul th:each="user,userStat : ${users}"><li>当前遍历的次数:<span th:text="${userStat.count}"/>当前遍历的索引:<span th:text="${userStat.index}"/>当前遍历是否是奇数行:<span th:text="${userStat.odd}"/>当前遍历是否是偶数行:<span th:text="${userStat.even}"/></li><li th:text="${user.id}"/><li th:text="${user.name}"/><li th:text="${user.age}"/><li th:text="${#dates.format(user.bir, 'yyyy年MM月dd日')}"/><li>集合中的总记录数: <span th:text="${userStat.size}"/></li></ul><h1>测试链接中的路径</h1><a th:href="@{/user/delete(id=99,name='赵六')}">删除记录</a></body>
</html>

访问:http://localhost:8080/user/findAll

SpringBoot 集成 Jsp、Thymeleaf 模板引擎 + Thymeleaf 基本使用相关推荐

  1. 九、SpringBoot集成Thymeleaf模板引擎

    Thymeleaf咋读!??? 呵呵,是不是一脸懵逼...哥用我的大学四级英文知识告诉你吧:[θaimlif]. 啥玩意?不会音标?...那你就这样叫它吧:"赛母李府",大部分中国 ...

  2. Spring Boot (四)模板引擎Thymeleaf集成

    一.Thymeleaf介绍 Thymeleaf是一种Java XML / XHTML / HTML5模板引擎,可以在Web和非Web环境中使用.它更适合在基于MVC的Web应用程序的视图层提供XHTM ...

  3. Spring Boot 最佳实践(四)模板引擎Thymeleaf集成

    ## 一.Thymeleaf介绍 Thymeleaf是一种Java XML / XHTML / HTML5模板引擎,可以在Web和非Web环境中使用.它更适合在基于MVC的Web应用程序的视图层提供X ...

  4. 【Springboot】SpringBoot基础知识及整合Thymeleaf模板引擎

    文章目录 SpringBoot简介 SpringBoot是什么 为什么要学习SpringBoot SpringBoot的优势 学习SpringBoot前要具备的基础 创建第一个SpringBoot项目 ...

  5. <12>springboot集成thymeleaf模板引擎

    创建一个springboot工程,导入以下依赖 <dependencies><!--springboot框架web组件依赖--><dependency><gr ...

  6. 玩转springboot:thymeleaf模板引擎入门程序

    一.前言 常用的模板引擎有:JSP.Velocity.Freemarker.Thymeleaf 但是,Springboot默认是不支持JSP的,默认使用thymeleaf模板引擎.而且,语法更简单,功 ...

  7. Spring Boot集成Thymeleaf模板引擎

    一.Thymeleaf 模板介绍 Spring Boot 推荐使用Thymeleaf 来代替传统开发中的JSP,那么什么是Thymeleaf 模板引擎呢?下面就来简单的介绍一下. Thymeleaf ...

  8. SpringBoot入门:新一代Java模板引擎Thymeleaf(理论)

    Spring Boot 提供了spring-boot-starter-web来为Web开发予以支持,spring-boot-starter-web为我们提供了嵌入的Tomcat以及SpringMVC的 ...

  9. Thymeleaf模板引擎---SpringBoot

    Thymeleaf模板引擎 前端交给我们的页面,是html页面.如果是我们以前开发,我们需要把他们转成jsp页面,jsp好处就是当我们查出一些数据转发到JSP页面以后,我们可以用jsp轻松实现数据的显 ...

最新文章

  1. 彻底理解 Spring 容器和应用上下文
  2. linux之 !!命令
  3. jaxb 映射 空字段_JAXB和未映射的属性
  4. python发邮件详解_python:利用smtplib发送邮件详解
  5. 跨境电商,独立站和第三方平台孰更具优势?
  6. 合理使用webpack提高开发效率
  7. shell之脚本片断
  8. python精妙算法_YOLOv4:高速物体检测的精妙之处
  9. 【jmeter教程——从入门到熟练】
  10. 高性能Nginx服务器+互联网高并发解决方案+安全架构 蚂蚁学堂互联网架构师课程
  11. 三年程序员成功转型项目经理
  12. js实现人物移动(附有全部代码以及解析)
  13. 职场历练【管理学之三】
  14. linux后台运行服务
  15. 【python 图片文字识别】pyocr图片文字识别
  16. SQLite FTS3 和 FTS4 插件
  17. SuperMap iClient3D for WebGL教程-管线流动特效
  18. 爱立信联手日本软银在东京进行5G测试
  19. Stocks:炒股相关的术语简介、炒股心得、经验
  20. 1.计算一个字节中有多少bit被置1

热门文章

  1. 产品的缺点要不要提前告诉客户?
  2. SQL数值计算函数之round(X,D)
  3. Java-线程中sleep()、wait()和notify()和notifyAll()、suspend和resume()、yield()、join()、interrupt()的用法和区别
  4. ssis 列转换_SSIS中的术语提取转换
  5. 组织架构递归_映射架构和递归管理数据–第2部分
  6. ajax的嵌套需要注意的问题
  7. Windows服务一直“正在启动”怎么杀
  8. awk分割列-【AWK学习之旅】
  9. 第二百五十八天 how can I 坚持
  10. web service 学习 2 -- 什么时候应该使用web service