springboot项目如何往html中插入数据
时间: 2023-12-23 21:02:46 浏览: 48
在Spring Boot项目中,往HTML中插入数据可以使用Thymeleaf模板引擎来实现。下面是一个简单的示例:
1.在Maven中添加Thymeleaf依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
2.在Controller中定义一个方法,用于返回HTML页面和需要插入的数据:
```
@RequestMapping("/")
public String index(Model model) {
model.addAttribute("name", "World");
return "index";
}
```
3.在resources/templates目录下创建一个名为index.html的文件,使用Thymeleaf语法来插入数据:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Insert Data Example</title>
</head>
<body>
<h1>Hello, <span th:text="${name}"></span>!</h1>
</body>
</html>
```
在上面的示例中,Thymeleaf使用th:text属性来插入数据,${name}表示从Controller传入的数据。
当访问http://localhost:8080/时,就会显示Hello, World!。