欢迎阅读我的博客,本文将介绍如何在Spring Boot中使用Thymeleaf模板引擎,并使用其基础语法th:,以及如何在Thymeleaf中获取request和session作用域的值。
概述
Thymeleaf是一个用于构建Java应用程序的现代服务器端Java模板引擎。它是一个强大且易于集成的模板引擎,具有灵活的语法和功能,可以轻松地集成到Spring Boot项目中。
准备工作
在开始之前,请确保已经安装了Java、Maven和Spring Boot。
创建Spring Boot项目
首先,在你的开发环境中创建一个新的Spring Boot项目。
$ spring init --name=thymeleaf-demo --dependencies=web thymeleaf-demo
添加Thymeleaf依赖
打开pom.xml
文件,并添加以下依赖:
<dependencies>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
...
</dependencies>
创建Thymeleaf模板文件
在src/main/resources/templates
目录下创建一个Thymeleaf模板文件index.html
,并在其中使用Thymeleaf的基础语法th:
。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Thymeleaf Demo</title>
</head>
<body>
<h1 th:text="${message}">Hello, World!</h1>
</body>
</html>
在上面的例子中,我们使用了th:text
属性来设置h1
元素的文本内容。在运行时,Thymeleaf会将${message}
替换为实际的值。
创建控制器
创建一个控制器类DemoController
,并将index.html
模板引入到方法中。
@Controller
public class DemoController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Hello, Spring Boot Thymeleaf!");
return "index";
}
}
在上面的例子中,index
方法将"Hello, Spring Boot Thymeleaf!"
添加到模型中,并将返回的视图名称设置为index
,该名称与模板的文件名相对应。
运行应用程序
现在我们可以运行应用程序了。执行以下命令:
$ mvn spring-boot:run
接着,打开浏览器并访问http://localhost:8080
,你将看到页面上显示的文本为Hello, Spring Boot Thymeleaf!
。
使用Thymeleaf获取request和session作用域的值
Thymeleaf不仅可以获取通过模型传递的值,还可以获取request和session作用域中的值。
获取request作用域的值
在DemoController
的index
方法中,我们添加了一个名为message
的值。现在,我们将演示如何在Thymeleaf中获取request作用域中的值。
@GetMapping("/")
public String index(HttpServletRequest request, Model model) {
request.setAttribute("message", "Hello, Spring Boot Thymeleaf!");
return "index";
}
在模板文件中,我们可以使用th:text
语法来获取request作用域中的值。
<h1 th:text="${#request.getAttribute('message')}">Hello, World!</h1>
获取session作用域的值
同样的方式,我们也可以获取session作用域中的值。
@GetMapping("/")
public String index(HttpSession session, Model model) {
session.setAttribute("message", "Hello, Spring Boot Thymeleaf!");
return "index";
}
在模板文件中,我们可以使用th:text
语法来获取session作用域中的值。
<h1 th:text="${#session.getAttribute('message')}">Hello, World!</h1>
结语
恭喜!你已经成功地创建了一个Spring Boot项目并使用Thymeleaf模板引擎。你还学会了如何使用Thymeleaf的基础语法th:
,以及如何在Thymeleaf中获取request和session作用域的值。现在你可以尝试去扩展和优化你的应用程序。
我希望本文能对你有所帮助。如果有任何问题或建议,请在下方留言,我会尽快回复。谢谢阅读!
本文来自极简博客,作者:星河之舟,转载请注明原文链接:Spring Boot 第一个Thymeleaf应用(基础语法th:,request、session作用域取值)