Spring Boot 項目集成 FreeMarker時,未進行正確配置的話會出現404錯誤,如圖所示:
Spring Boot 要集成 FreeMarker 模板引擎時必須經過正確的配置,大致可分爲5 個步驟:
- 引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
- 在application.yml文件中進行如下配置,務必配置正確(.properties文件也一樣)
freemarker:
template-loader-path: classpath:/templates # classpath: 一定不能漏寫
cache: false
charset: UTF-8
check-template-location: true
content-type: text/html
expose-request-attributes: false
expose-session-attributes: false
request-context-attribute: req
suffix: .ftl
曾經因爲漏寫 classpath: ,花了1個小時找不到原因
- 編寫controller類
@Controller
@RequestMapping("/")
public class OrderController {
@GetMapping("/list")
public ModelAndView list(Map<String, Object> map) {
map.put("name", "chenf24k");
return new ModelAndView("name", map);
}
}
- 在Spring Boot項目的resources/templates下新建 name.ftl模板文件
<h1>FreeMarker</h1>
<h2>${name}</h2>
- 啓動Spring Boot 項目後瀏覽器輸入地址: http://127.0.0.1:8080/list 進行訪問