Skip to content
鼓励作者:欢迎打赏犒劳

01-Thymeleaf

依赖

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

生成模版文件

java
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Controller
public class ExampleController {

    private final TemplateEngine templateEngine;

    public ExampleController(TemplateEngine templateEngine) {
        this.templateEngine = templateEngine;
    }

    @GetMapping("/generateFile")
    public ResponseEntity<ByteArrayResource> generateFile() throws IOException {
        Context context = new Context();
        context.setVariable("title", "Thymeleaf Example");
        context.setVariable("message", "This is a message from the controller.");

        String htmlContent = templateEngine.process("example", context);
        
        // 将 HTML 内容转为字节数组
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(htmlContent.getBytes());
        ByteArrayResource resource = new ByteArrayResource(outputStream.toByteArray());

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=example.html")
                .contentType(MediaType.TEXT_HTML)
                .body(resource);
    }
}

src/main/resources/templates 目录下创建一个 Thymeleaf 模板文件,例如 example.html

html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>My Example</title>
</head>
<body>
    <h1 th:text="${title}">Default Title</h1>
    <p th:text="${message}">Default message</p >
</body>
</html>

如有转载或 CV 的请标注本站原文地址