第一步 Spring Boot工程默認是支持freemarker模板的,需要在pom中添加如下內容:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
第二步 資源文件application.properties中寫下如下配置:
# freemarker 配置信息
# ftl文件路徑
spring.freemarker.template-loader-path=classpath:/templates
# 緩存開關
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
第三步 resources/templates目錄下生成ftl文件,比如:index.ftl
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h1>${name}</h1>
</body>
</html>
name是一個變量,從後臺傳遞過來的,不寫也沒關係
第四步 生成controller文件,比如:
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Controller
public class IndexController {
@GetMapping("/")
public String index(Model m){
// 這裏的name便是上面ftl文件中要顯示的內容
m.addAttribute("name", "my name is Tomcat.");
return "index";
}
}
第五步 啓動容器,輸入地址 http://localhost:8080/ 就能看到效果了