spring boot 使用thymeleaf新建页面
时间: 2023-06-24 21:07:32 浏览: 63
要在Spring Boot中使用Thymeleaf新建页面,可以按照以下步骤进行操作:
1. 确认在Spring Boot项目中已经添加了Thymeleaf依赖,在pom.xml文件中添加如下代码:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2. 在src/main/resources/templates目录下新建一个HTML文件,例如index.html。
3. 在HTML文件中添加Thymeleaf的命名空间,并编写HTML页面内容。示例如下:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Thymeleaf Example</title>
</head>
<body>
<h1 th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
```
4. 在Spring Boot的Controller中注入Model对象,并设置需要传递给页面的参数。示例如下:
```java
@Controller
public class MyController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("name", "Thymeleaf");
return "index";
}
}
```
5. 运行Spring Boot项目,访问http://localhost:8080/,即可看到渲染后的页面。
以上就是在Spring Boot中使用Thymeleaf新建页面的基本步骤。