Springboot中怎么選擇性使用thymeleaf進(jìn)行渲染?
Spring Boot 默認(rèn)支持多種模板引擎,包括 Thymeleaf。如果你想選擇性地使用 Thymeleaf 進(jìn)行渲染,這基本上取決于你的 Controller 的實(shí)現(xiàn)。以下是一個(gè)基本示例:
首先,確保你的 Spring Boot 項(xiàng)目已經(jīng)添加了 Thymeleaf 的依賴(lài)。在你的 pom.xml
文件中,你應(yīng)該看到類(lèi)似以下的內(nèi)容
<dependency>
? ?<groupId>org.springframework.boot</groupId>
? ?<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
接著,你可以在 Controller 中返回一個(gè) ModelAndView 或者一個(gè) String 來(lái)決定是否使用 Thymeleaf 渲染。例如:
@Controller
public class MyController {
? ?@RequestMapping("/thymeleaf")
? ?public String thymeleaf(Model model) {
? ? ? ?model.addAttribute("message", "Hello, Thymeleaf!");
? ? ? ?return "thymeleaf-template";
? ?}
? ?@RequestMapping("/plain")
? ?public ResponseEntity<String> plain() {
? ? ? ?return new ResponseEntity<>("Hello, Plain Response!", HttpStatus.OK);
? ?}
}
在這個(gè)例子中,如果你訪問(wèn) /thymeleaf
URL,那么你的請(qǐng)求將會(huì)被渲染成 Thymeleaf 模板(你需要在你的模板目錄中有一個(gè)名為 thymeleaf-template.html
的文件)。而如果你訪問(wèn) /plain
URL,那么你將會(huì)收到一個(gè)純文本的 HTTP 響應(yīng),沒(méi)有使用 Thymeleaf 渲染。
記住,要使 Thymeleaf 渲染生效,你需要在模板目錄(默認(rèn)是 src/main/resources/templates
)中有對(duì)應(yīng)的 Thymeleaf 模板文件。
這就是在 Spring Boot 中選擇性使用 Thymeleaf 的基本方式。具體的實(shí)現(xiàn)可能會(huì)根據(jù)你的項(xiàng)目需求和架構(gòu)而有所不同。