Springboot 渲染页面
时间: 2023-05-25 18:05:38 浏览: 77
在 Springboot 中,一般使用 Thymeleaf 模板引擎来渲染页面。
1. 添加 Thymeleaf 依赖
在 pom.xml 文件中添加 Thymeleaf 和 Springboot Thymeleaf 的依赖:
```xml
<dependencies>
...
<!--Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
...
</dependencies>
```
2. 创建 HTML 页面
在 src/main/resources/templates 目录下创建 HTML 页面,例如 index.html:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Springboot Thymeleaf</title>
</head>
<body>
<h1>Hello, Thymeleaf!</h1>
<p th:text="${message}"></p>
</body>
</html>
```
在 HTML 页面中,使用 Thymeleaf 的语法来设置变量值,例如上面的 ${message} 变量就需要在后面的代码中指定它的值。
3. 创建 Controller
在 Springboot 的 Controller 类中添加处理请求的方法,例如 HomeController:
```java
@Controller
public class HomeController {
@GetMapping("/")
public String index(Model model) {
model.addAttribute("message", "Welcome to Springboot Thymeleaf!");
return "index";
}
}
```
该方法会接收 GET 方法的请求并返回 index.html 页面。
在方法中,使用 model 对象来传递变量值,例如上面的 "message" 变量就是通过 model.addAttribute("message", "Welcome to Springboot Thymeleaf!") 语句传递的。
其中,返回值 "index" 是 HTML 页面的文件名(不需要后缀名),Springboot 会自动在 templates 目录下查找该文件并渲染它。
4. 运行应用程序
运行 Springboot 应用程序,访问 http://localhost:8080/ ,可以看到渲染好的 HTML 页面。
总结一下,渲染 Springboot 页面的主要步骤如下:
1. 添加 Thymleaf 依赖;
2. 创建 HTML 页面,使用 Thymeleaf 语法设置变量值;
3. 创建 Controller 类,在方法中使用 model 对象传递变量值并返回 HTML 页面的文件名;
4. 运行应用程序,访问相应的 URL,查看渲染结果。