在Spring Boot中,渲染输出HTML文档模板通常是通过整合模板引擎(如Thymeleaf、FreeMarker或Mustache)来实现的。以下是使用Thymeleaf作为模板引擎的例子,但其他模板引擎的使用方法也类似。
1. 添加依赖首先,在pom.xml文件中添加Thymeleaf依赖:
<dependencies> <!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Thymeleaf dependency --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> </dependencies>2. 创建HTML模板
在src/main/resources/templates目录下创建一个Thymeleaf模板文件,例如index.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <title>Spring Boot Thymeleaf Example</title> </head> <body> <h1 th:text="${message}">Hello, World!</h1> </body> </html>3. 创建Controller
创建一个Spring MVC控制器来处理请求并渲染模板。在src/main/java/com/example/demo目录下创建一个控制器类,例如HomeController:
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping("/") public String home(Model model) { model.addAttribute("message", "Welcome to Spring Boot with Thymeleaf!"); return "index"; // 返回模板文件的名称(不带扩展名) } }4. 启动应用
创建应用程序的主类,确保它位于src/main/java/com/example/demo目录下:
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }5. 运行应用
运行Spring Boot应用程序,然后在浏览器中访问http://localhost:8080,你应该会看到渲染的HTML页面,显示“Welcome to Spring Boot with Thymeleaf!”。
使用其他模板引擎如果你想使用其他模板引擎,比如FreeMarker或Mustache,只需在pom.xml中添加相应的依赖,并按照模板引擎的语法编写模板文件。以下是添加FreeMarker依赖的例子:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
然后在src/main/resources/templates目录下创建一个FreeMarker模板文件,例如index.ftl:
<!DOCTYPE html> <html> <head> <title>Spring Boot FreeMarker Example</title> </head> <body> <h1>${message}</h1> </body> </html>
控制器的代码可以保持不变,因为Spring Boot会自动检测和使用正确的模板引擎。
通过这种方式,Spring Boot可以很方便地使用模板引擎来渲染输出HTML文档。
网友回复
DLNA与UPnP的区别和不同?
苏超自建抢票app,通过先预约再抽签化解高并发抢票?
python如何让给电脑在局域网中伪装成电视接收手机的投屏图片视频播放?
如何结合python+js如何自己的视频编码与加密播放直播?
python如何在电脑上通过局域网将本地视频或m3u8视频投屏电视播放?
腾讯视频爱奇艺优酷vip电影电视剧视频如何通过python绕过vip收费直接观看?
有没有可免费观看全球电视台直播m3u8地址url的合集?
有没有实现观影自由的免vip影视苹果 CMS V10 API的可用url?
python如何实时检测电脑usb插入检测报警?
如何判断真人操作的鼠标移动直线轨迹与机器操作的轨迹?