Spring Boot 提供了不少模板引擎的支持,例如 FreeMarker、Thymeleaf。这篇,咱们看下 Spring Boot 如何集成和使用 FreeMarker。javascript
博客地址:blog.720ui.com/html
Spring Boot 中使用 FreeMarker 模板很是简单方便。若是想要使用FreeMarker 模板引擎,首先,修改 POM 文件,添加依赖。前端
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>复制代码
而后,咱们建立模板。值得注意的是,Spring Boot 集成的 FreeMarker 默认的配置文件放在 classpath:/templates/。所以,咱们须要在 src/main/resources/templates/ 添加模板文件。java
例如,咱们添加一个模板文件,叫作 welcome.ftl。git
<!DOCTYPE html>
<html lang="en"> <body> Date: ${time?date}<br> Message: ${message} </body> </html>复制代码
那么,最后一步,咱们在控制类中只须要这么配置就能够了。github
@Controller("template.freemarkerController")
public class WelcomeController {
@RequestMapping("/template/freemarker/welcome")
public String welcome(Map<String, Object> model) {
model.put("time", new Date());
model.put("message", "梁桂钊");
return "welcome";
}
}复制代码
还记得咱们以前的 WebMain 么,咱们来回顾下。spring
@RestController
@EnableAutoConfiguration
@ComponentScan(basePackages = { "com.lianggzone.springboot" })
public class WebMain {
public static void main(String[] args) throws Exception {
SpringApplication.run(WebMain.class, args);
}
}复制代码
直接运行 WebMain 类,或者能够经过“mvn spring-boot:run”在命令行启动该应用。会启动一个内嵌的 Tomcat 服务器运行在 8080 端口。访问 “http://localhost:8080/template/freemarker/welcome” 能够看到页面上显示结果。后端
上面的场景,是很是典型的 MVC 的使用场景,咱们经过 FreeMaker 代替 JSP 做为页面渲染。可是,随着,先后端分离,JSP 渐渐远离咱们的视野,服务端更多地处理业务逻辑,经过 RESTful 或者 RPC 对外提供服务。页面的交互,交给前端作渲染。springboot
这种状况下,是否是 FreeMarker 就没有用武之地了呢?实际上,FreeMarker 做为模板引擎,还有不少使用场景,例如,咱们能够把咱们能够动静分离,把相对不会变化的内容经过 FreeMarker 渲染生成静态文件上传到内容服务,内容服务经过 CDN 进行资源分发。服务器
那么,咱们对上面的代码进行一个小改造,模拟一个文件生成到本地的场景。
@RestController("template.freemarkerController2")
@EnableAutoConfiguration
public class Welcome2Controller {
@Autowired
private Configuration configuration;
@RequestMapping("/template/freemarker/welcome2")
public String welcome2(Map<String, Object> model) throws Exception {
model.put("time", new Date());
model.put("message", "梁桂钊");
Template template = configuration.getTemplate("welcome.ftl");
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
FileUtils.writeStringToFile(new File("d:/welcome.html"), content);
return "welcome";
}
}复制代码
直接运行 WebMain 类,访问 “http://localhost:8080/template/freemarker/welcome2” 能够看到页面上显示结果,并查看D盘,是否生成文件了呢?
相关示例完整代码: springboot-action
(完)
更多精彩文章,尽在「服务端思惟」微信公众号!