springboot 如何通過SpringTemplateEngine渲染html
要單獨獲取到渲染后的 HTML 字符串,便于進行其他操作,可以通過以下幾種方式實現(xiàn)。常見的用法是通過 Spring 的 Thymeleaf 模板引擎渲染模板為 HTML 字符串,而不是直接將其輸出到瀏覽器。這樣你就可以對渲染后的字符串進行其他操作,比如保存到文件或進一步處理。
1. 使用 Thymeleaf 渲染為字符串
你可以使用 Thymeleaf 的 TemplateEngine 手動渲染模板為字符串。需要通過 TemplateEngine 渲染模板文件,并且將渲染后的 HTML 作為一個字符串返回。你可以創(chuàng)建一個自定義的服務來處理這個需求。
1.1 添加依賴
除了 Thymeleaf 依賴之外,還需要確保有 Spring Web 和 Thymeleaf 依賴在 pom.xml 中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>1.2 自定義服務類渲染 Thymeleaf 模板為字符串
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import java.util.Map;
@Service
public class HtmlRenderingService {
private final TemplateEngine templateEngine;
public HtmlRenderingService(TemplateEngine templateEngine) {
this.templateEngine = templateEngine;
}
public String renderHtml(String templateName, Map<String, Object> variables) {
// 創(chuàng)建一個上下文對象
Context context = new Context();
// 將傳遞的變量設置到上下文
context.setVariables(variables);
// 渲染指定模板為字符串
return templateEngine.process(templateName, context);
}
}templateEngine.process()會根據(jù)提供的模板名稱和上下文變量,渲染出最終的 HTML 字符串。variables是一個Map對象,用于傳遞到模板中的變量。
1.3 控制器調(diào)用服務類渲染 HTML 字符串
你可以在控制器中調(diào)用這個服務,將模板渲染為字符串,并執(zhí)行你想要的操作(如返回、保存、日志等)。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HtmlRenderController {
@Autowired
private HtmlRenderingService htmlRenderingService;
@GetMapping("/render-html")
public String renderHtml() {
// 假設要傳遞的熱點資源和推薦資源數(shù)據(jù)
HotResource hotResource = new HotResource("熱點資源1", "12345", "67890");
Map<String, Object> variables = new HashMap<>();
variables.put("hotResource", hotResource);
return htmlRenderingService.renderHtml("resources", variables);
}
}在上面的代碼中,當你訪問 /render-html 這個接口時,控制器會調(diào)用 HtmlRenderingService 服務,將 resources.html 模板渲染為字符串并返回。
1.4 Thymeleaf 模板文件 (resources.html)
你可以使用和之前一樣的 Thymeleaf 模板文件進行動態(tài)渲染,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>資源推薦</title>
<!-- 樣式略 -->
</head>
<body>
<div class="container">
<div class="section">
<h2>熱點資源</h2>
<div class="item hot-resource">
<a th:href="@{/resource/hot(id=${hotResource.resourceId})}" rel="external nofollow" target="_blank" th:text="${hotResource.name}">熱點資源名稱</a>
<p th:text="'資源ID:' + ${hotResource.resourceId}">資源ID</p>
<p th:text="'熱點記錄ID:' + ${hotResource.recordId}">熱點記錄ID</p>
</div>
</div>
</div>
</body>
</html>2. 渲染 HTML 后進行其他操作
通過上述方式獲取的 HTML 字符串,你可以在控制器中進行任意操作:
- 返回 HTML 字符串:直接返回渲染后的 HTML 字符串給前端。
- 保存 HTML 文件:將 HTML 字符串保存到服務器上的某個文件。
- 傳遞到其他服務:你可以將這個字符串發(fā)送到其他服務或系統(tǒng)。
例如,將渲染后的 HTML 保存為文件:
import java.io.FileWriter;
import java.io.IOException;
public class HtmlFileWriter {
public static void saveHtmlToFile(String htmlContent, String filePath) throws IOException {
FileWriter fileWriter = new FileWriter(filePath);
fileWriter.write(htmlContent);
fileWriter.close();
}
}在控制器中調(diào)用這個方法:
@GetMapping("/save-html")
public String saveHtmlToFile() {
HotResource hotResource = new HotResource("熱點資源1", "12345", "67890");
Map<String, Object> variables = new HashMap<>();
variables.put("hotResource", hotResource);
String renderedHtml = htmlRenderingService.renderHtml("resources", variables);
try {
HtmlFileWriter.saveHtmlToFile(renderedHtml, "/path/to/save/file.html");
return "HTML file saved successfully!";
} catch (IOException e) {
e.printStackTrace();
return "Failed to save HTML file!";
}
}總結
通過上述方案,你可以:
- 動態(tài)渲染 HTML 頁面為字符串。
- 根據(jù)需要返回 HTML 字符串、保存到文件或進行其他處理。
使用 Thymeleaf 渲染為字符串的方式非常靈活,適合你進行更多自定義操作。
到此這篇關于springboot 通過SpringTemplateEngine渲染html的文章就介紹到這了,更多相關springboot 渲染html內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java實現(xiàn)基于JDBC操作mysql數(shù)據(jù)庫的方法
這篇文章主要介紹了Java實現(xiàn)基于JDBC操作mysql數(shù)據(jù)庫的方法,結合實例形式分析了java使用JDBC實現(xiàn)針對mysql數(shù)據(jù)庫的連接、查詢、輸出等相關操作技巧,需要的朋友可以參考下2017-12-12
SpringBoot+隨機鹽值+雙重MD5實現(xiàn)加密登錄
數(shù)據(jù)加密在很多項目上都可以用到,大部分都會采用MD5進行加密,本文主要介紹了SpringBoot+隨機鹽值+雙重MD5實現(xiàn)加密登錄,具有一定的參考價值,感興趣的可以了解一下2024-02-02
在Spring AI中實現(xiàn)函數(shù)調(diào)用的方法
在SpringAI中實現(xiàn)函數(shù)調(diào)用,通過反射機制與AOP技術,靈活高效地處理業(yè)務邏輯,本文詳細介紹了基本原理、應用場景及Java代碼示例,涵蓋直接調(diào)用、AOP增強和異步調(diào)用三種方式,需要的朋友可以參考下2026-05-05
如何在 Java 中實現(xiàn)一個 redis 緩存服務
為什么要使用緩存?說到底是為了提高系統(tǒng)的運行速度。將用戶頻繁訪問的內(nèi)容存放在離用戶最近,訪問速度最快的地方,提高用戶的響應速度。下面我們來一起深入學習一下吧2019-06-06
win7 64位系統(tǒng)JDK安裝配置環(huán)境變量教程
這篇文章主要為大家詳細介紹了win7 64位系統(tǒng)JDK安裝配置環(huán)境變量教程,感興趣的小伙伴們可以參考一下2016-06-06
Nacos服務發(fā)現(xiàn)并發(fā)啟動scheduleUpdate定時任務的流程分析
這篇文章主要介紹了Nacos服務發(fā)現(xiàn)并發(fā)啟動scheduleUpdate定時任務,本文結合實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-02-02

