溫馨提示×

springboot中freemarker怎么加載模板

小億
95
2024-05-24 10:34:20
欄目: 編程語言

在Spring Boot應(yīng)用中加載Freemarker模板需要進(jìn)行以下步驟:

  1. 首先需要在pom.xml文件中添加Freemarker依賴:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  1. 創(chuàng)建Freemarker模板文件,通常會存放在src/main/resources/templates目錄下。

  2. 在Spring Boot應(yīng)用中創(chuàng)建一個(gè)Controller類,用于處理請求并返回Freemarker模板:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping("/")
    public String home() {
        return "index"; // 返回模板文件名,不需要加后綴
    }
}
  1. application.propertiesapplication.yml文件中配置Freemarker相關(guān)的屬性,如模板文件的存放路徑等。例如,在application.properties中添加以下配置:
spring.freemarker.template-loader-path=classpath:/templates/
spring.freemarker.suffix=.ftl
  1. 啟動(dòng)Spring Boot應(yīng)用后,訪問對應(yīng)的URL即可加載并顯示Freemarker模板。

注意:以上示例中的模板文件名為index.ftl,實(shí)際使用時(shí)可以根據(jù)需要?jiǎng)?chuàng)建不同的模板文件,并在Controller中返回對應(yīng)的模板文件名。

0