本篇博文将和大家一起使用Spring Boot 2.0 和FreeMarker 模板引擎整合实战。
1. 创建新的项目
2. 填写项目配置信息
3. 勾选web 模块
4. 勾选freemarker模板引擎模块
5.填写项目名称和项目保存路径
6. 修改POM文件,添加Freemarker 项目依赖
4.0.0 com.xingyun spring-boot-with-freemarker-sample 0.0.1-SNAPSHOT jar spring-boot-with-freemarker-sample Demo project for Spring Boot org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE UTF-8 UTF-8 1.8 org.springframework.boot spring-boot-starter-freemarker org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
7. 配置applicaiton.properties
# 设定ftl文件路径spring.freemarker.template-loader-path=classpath:/templatesspring.freemarker.cache=falsespring.freemarker.charset=UTF-8spring.freemarker.check-template-location=truespring.freemarker.content-type=text/htmlspring.freemarker.expose-request-attributes=falsespring.freemarker.expose-session-attributes=falsespring.freemarker.request-context-attribute=requestspring.freemarker.suffix=.ftl
Tips: 其实我试了下,把.ftl 换成.jsp ,创建JSP 文件也是可以的。
8. 创建文件夹和ftl格式文件
index.ftl
Title this is index page
welcome.ftl
Title this is welcome page
9. 创建 Controller
package com.xingyun.springbootwithfreemarkersample.controller;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@Controllerpublic class HomeController { @RequestMapping(value = "/") public String index(){ return "views/index"; } @RequestMapping(value = "/welcome") public String home(){ return "views/welcome"; }}
Tips: 由于要返回模板页面文件,所以我们只能使用@Controller 而不可以使用@RestController
10. 访问
11. 访问