1. 程式人生 > 程式設計 >Spring Boot如何整合FreeMarker模板引擎

Spring Boot如何整合FreeMarker模板引擎

POM

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

專案結構

src/
 +- main/
   +- java/
   |  +- com
   |    +- controller/
   |    |  +- IndexController.class
   |    +- Application.class
   +- resources/
     +- templates/
       +- index.ftlh
  • Application為應用程式啟動類
  • IndexController為控制器,裡面含有一個index請求處理方法,它返回index字串,表示渲染模板檔案index.ftlh。
  • index.ftlh為freemarker模板檔案

Applciation.class

@SpringBootApplication
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class,args);
  }
}

IndexController.class

@Controller
public class IndexController {
  @GetMapping("/index")
  public String index(Model model) {
    model.addAttribute("name","Alice");
    return "index";
  }
}

注意@ResponseBody註解不能和freemarker一起使用,所以此處不能標註@RestController註解。

index.ftlh

<!DOCTYPE html>
<html>
<head>
  <title>test</title>
</head>
<body>
hello ${name}!
</body>
</html>

執行

執行Application類裡的main方法。

然後訪問localhost:8080/index,結果展示為:

hello Alice!

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。