springboot项目如何往html中插入数据后返回前端该html页面
时间: 2024-05-16 10:15:46 浏览: 173
可以使用Thymeleaf模板引擎来实现将数据插入到HTML页面中并返回给前端。
首先,在Spring Boot项目的pom.xml文件中添加Thymeleaf依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
然后在Controller中编写一个方法,该方法返回HTML页面的名称和需要插入到页面中的数据:
```java
@Controller
public class ExampleController {
@GetMapping("/")
public String home(Model model) {
String message = "Hello, world!";
model.addAttribute("message", message);
return "home";
}
}
```
在上面的例子中,我们将一个字符串"Hello, world!"添加到Model中,并将其命名为"message"。然后将HTML页面的名称"home"作为返回值。
接下来,在HTML页面中使用Thymeleaf语法将数据插入到页面中:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
</head>
<body>
<h1 th:text="${message}"></h1>
</body>
</html>
```
在上面的例子中,我们使用Thymeleaf语法`${message}`将Model中的"message"数据插入到页面中的`<h1>`标签中。
最后,当用户访问根路径"/"时,将返回包含"Hello, world!"信息的HTML页面。
阅读全文
相关推荐


















