Spring Boot 提供了很多模板引擎的支持,例如 FreeMarker、Thymeleaf。这篇,我们看下 Spring Boot 如何集成和使用 FreeMarker。
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/ 添加模板文件。
例如,我们添加一个模板文件,叫做 welcome.ftl。
<!DOCTYPE html>
<html lang="en">
<body>
Date: ${time?date}<br>
Message: ${message}
</body>
</html>
那么,最后一步,我们在控制类中只需要这么配置就可以了。
@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 么,我们来回顾下。
@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 对外提供服务。页面的交互,交给前端做渲染。
这种情况下,是不是 FreeMarker 就没有用武之地了呢?实际上,FreeMarker 作为模板引擎,还有很多使用场景,例如,我们可以把我们可以动静分离,把相对不会变化的内容通过 FreeMarker 渲染生成静态文件上传到内容服务,内容服务通过 CDN 进行资源分发。
那么,我们对上面的代码进行一个小改造,模拟一个文件生成到本地的场景。
@RestController("template.freemarkerController2")
@EnableAutoConfiguration
public class Welcome2Controller {
@Autowired
private Configuration configuration;
@RequestMapping("/template/freemarker/welcome2")
public String welcome2(Map
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盘,是否生成文件了呢?