当前位置: 首页 > news >正文

SpringBoot——整合Thymeleaf模板

目录

模板引擎

新建一个SpringBoot项目

pom.xml

application.properties

Book

BookController

bookList.html

​编辑 项目总结


模板引擎

  • 模板引擎是为了用户界面与业务数据分离而产生的,可以生成特定格式的页面
  • 在Java中,主要的模板引擎有JSP(少用),Thyemeleaf,FreeMarker,Velocity等
  • 现在的大趋势是前后端分离开发,但如果自己写一些练手项目,使用模板引擎更快更方便
  • Thymeleaf可以快速实现表单绑定、属性编辑器、国际化等功能
  • Thymeleaf的基本语法规则:
    • 1、基础语法 - Thymeleaf 教程 (hxstrive.com)
    • 2、http://t.csdnimg.cn/aFWSO
    • 3、http://t.csdnimg.cn/Oa4rZ
  • 在此之前,控制器都是直接返回字符串,或者是跳转到其他URL地址,但使用Thymeleaf后,就可以让控制器跳转到项目中的某个 .html 文件
  • SpringBoot项目中所有页面文件都要放在 src/main/resources/templates 目录下,静态文件放在 src/main/static 目录下

项目总结

  1. 添加Thymeleaf依赖:首先,在你的Spring Boot项目的pom.xml文件中添加Thymeleaf的依赖。这样Spring Boot会自动配置Thymeleaf。
  2. 创建Thymeleaf模板文件:在src/main/resources/templates目录下创建Thymeleaf模板文件。Thymeleaf使用HTML文件作为模板,你可以在其中使用Thymeleaf的语法来动态渲染页面。
  3. 创建控制器:创建一个Spring MVC控制器,在其中设置需要在模板中渲染的数据。
  4. 启动应用程序:运行Spring Boot应用程序,访问控制器中定义的URL,应该会看到使用Thymeleaf模板渲染的页面。

  • 在项目开发中将Spring Boot框架、Thymeleaf与Spring MVC的视图技术及SpringBoot 的自动化配置集成在一起非常简便,不需要额外的配置,在开发中只需要关注Thymeleaf的语法即可

新建一个SpringBoot项目

项目结构:

pom.xml

主要引入Thymeleaf依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><!--最初的3.2.5版本太高了,需要手动降低成2.3.12--><version>2.3.12.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com</groupId><artifactId>springboot_thymeleaf</artifactId><version>0.0.1-SNAPSHOT</version><name>springboot_thymeleaf</name><description>Demo project for Spring Boot</description><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--添加Thymeleaf依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

application.properties

spring.application.name=springboot_thymeleaf
server.port=8080
# 访问template下的html文件
spring.thymeleaf.prefix=classpath:/templates/
# 开发时关闭缓存,不然没法看到实时页
spring.thymeleaf.cache=false
# 设置Thymeleaf页面的后缀为.html
spring.thymeleaf.suffix=.html

Book实体类

package com.springboot_thymeleaf;import java.util.Date;/*** 实体类*/
public class Book {private Integer id;private String name;private Date createTime;private String author;//getter,setter方法
}

BookController控制器

  • Thymeleaf会根据控制器返回的字符串值,寻找templates文件夹下同名的网页文件,并跳转至该网页文件,比如下例,就是跳转到bookList.html文件
  • 在 Spring 框架中,ModelModelAndView 是用于在控制器中向视图传递数据的两种方式,在 Spring Boot 项目中,通常建议使用 Model,因为它更简单直观,适合大多数情况。只有在需要更复杂的场景或更精确地控制视图名称时,才需要使用 ModelAndView

package com.springboot_thymeleaf.controller;import com.springboot_thymeleaf.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;/*** @Controller:这是一个Spring框架的注解,它用于将类标记为控制器(Controller)。* 使用@Controller注解的类被Spring认为是处理HTTP请求的控制器,* 并且可以处理来自客户端的请求。它通常与@RequestMapping注解一起使用,用于映射URL路径到相应的处理方法。*/
@Controller
public class BookController {/*** @GetMapping("/books"): 这是一个Spring框架的注解,它用于映射HTTP GET请求到处理方法。* 在BookController中,@GetMapping("/books")注解表示当浏览器发起GET请求到"/books"路径时,* 将调用books()方法来处理该请求。books()方法会返回一个ModelAndView对象,用于渲染书籍列表的视图。*/@GetMapping("/books")public String books(Model model){// 添加两本书的记录List<Book> books = new ArrayList<>();Book book1 = new Book();book1.setId(1);book1.setName("Spring Boot企业级应用开发");book1.setCreateTime(new Date());book1.setAuthor("李白");Book book2 = new Book();book2.setId(2);book2.setName("Node.js Web开发实战");book2.setCreateTime(new Date());book2.setAuthor("白居易");books.add(book1);books.add(book2);// 使用addAttribute(String attributeName, Object attributeValue)方法向Model中添加属性。// 属性的名称是一个字符串,可以在视图中使用它来检索属性值。属性值可以是任何Java对象,例如字符串、数字、集合等。model.addAttribute("books", books);return "bookList.html";}
}

bookList.html动态网页文件

<!DOCTYPE html>
<!--导入Thymeleaf的命名空间-->
<html lang="en" xmlns: xmlns:th="http://www.w3.org/1999/xhtml">
<head><meta charset="UTF-8"><title>图书列表</title>
</head>
<body>
<table border="1" width="100%"><tr><td>序号</td><td>书名</td><td>作者</td></tr><!--${}: 变量表达式,Thymeleaf获取一个值的语法是th:text="${title}"--><tr th:each="book:${books}"><!--四个单元格内容--><td th:text="${book.id}"/><td th:text="${book.name}"/><td th:text="${#dates.format(book.createTime,'yyyy-MM-dd')}"/><td th:text="${book.author}"/></tr>
</table></body>
</html>

启动项目,浏览器访问http://localhost:8080/books

http://www.lryc.cn/news/358048.html

相关文章:

  • 电商推荐系统+电影推荐系统【虚拟机镜像分享】
  • (函数)判断素数(C语言)
  • git 学习随笔
  • 【因果推断python】1_因果关系初步1
  • (函数)颠倒字符串顺序(C语言)
  • 自定义数据集上的3D目标检测:使用OpenPCDet训练CenterPointPillar模型
  • 音乐传奇告别之作:《杰作》未解之谜❗❗
  • 【Postman接口测试】第四节.Postman接口测试项目实战(上)
  • opencv学习备份
  • Unity 中获取调用者方法名
  • k8s集群中pod的容器资源限制和三种探针
  • tar 详细说明
  • 渗透测试工具Cobalt strike-2.CS基础使用
  • 【UE5.1 角色练习】08-物体抬升、抛出技能 - part2
  • Java面试题--JVM大厂篇(1-10)
  • 【知识拓展】机器学习基础(一):什么是预处理对象、模型对象 、pipeline、Tokenizer
  • Linux dig 命令
  • 后台接口返回void有设置response相关内容,前端通过open打开接口下载excel文件
  • scp问题:Permission denied, please try again.
  • new CCDIKSolver( OOI.kira, iks ); // 创建逆运动学求解器
  • 【Go】Swagger v2 转 OpenApi v3 CLI - swag2op
  • python Z-score标准化
  • 人工智能的数学基础(高数)
  • React(四)memo、useCallback、useMemo Hook
  • 前端介绍及工具环境搭建
  • uniapp高校二手书交易商城回收系统 微信小程序python+java+node.js+php
  • Vue3 图片或视频下载跨域或文件损坏的解决方法
  • vue2和3区别
  • 倍福TwinCAT3 PLC编程软件下载安装
  • Linux一键式管理jar程序执行周期【完整脚本复制可用】