Spring Boot 视图层集成:Thymeleaf、Freemarker 与 Velocity 实战
在 Spring Boot 的 Web 开发中,视图层负责将后端数据渲染为前端页面。虽然现代前后端分离架构很流行,但在管理后台、传统企业应用或快速原型开发中,服务端渲染(SSR)依然高效且必要。Spring Boot 对主流模板引擎提供了开箱即用的支持,主要包括 Thymeleaf、Freemarker 和 Velocity。
1. 统一的后端基础
无论选择哪种模板引擎,后端的实体类、Repository 和 Controller 逻辑基本一致。为了减少重复代码,我们首先搭建好通用的数据模型和控制层。
依赖配置
在 pom.xml 中引入 Web 和数据访问依赖即可,具体模板引擎依赖会在后续章节单独添加。
<dependencies>
<!-- Web 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Data JPA 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- H2 数据库依赖 (仅用于演示) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
org.springframework.boot
spring-boot-starter-test
test


