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(); // 將傳遞的變量設(shè)置到上下文 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è)要傳遞的熱點資源和推薦資源數(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!"; } }
總結(jié)
通過上述方案,你可以:
- 動態(tài)渲染 HTML 頁面為字符串。
- 根據(jù)需要返回 HTML 字符串、保存到文件或進行其他處理。
使用 Thymeleaf 渲染為字符串的方式非常靈活,適合你進行更多自定義操作。
到此這篇關(guān)于springboot 通過SpringTemplateEngine渲染html的文章就介紹到這了,更多相關(guān)springboot 渲染html內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
spring-boot報錯java: 程序包javax.servlet.http不存在
當springboot項目從2.7.x的升級到3.0.x的時候,會遇到一個問題java: 程序包javax.servlet.http不存在,下面就來具體介紹一下,感興趣的可以了解一下2024-08-08SpringBoot3中Spring?WebFlux?SSE服務器發(fā)送事件的實現(xiàn)步驟
本文介紹了如何使用SpringBoot3和響應式編程實現(xiàn)服務器發(fā)送事件(SSE),并討論了其在實時數(shù)據(jù)推送場景中的優(yōu)勢,通過示例代碼,展示了如何創(chuàng)建SSE控制器、客戶端接收數(shù)據(jù)以及優(yōu)化與擴展,感興趣的朋友跟隨小編一起看看吧2024-11-11java system類使用方法示例 獲取系統(tǒng)信息
這篇文章主要介紹了java system類使用方法,該類中的方法都是靜態(tài)的。不能被實例化,沒有對外提供構(gòu)造函數(shù),該類可以獲取系統(tǒng)信息2014-01-01