+
95
-

回答

在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文档。

网友回复

我知道答案,我要回答