發表於 | Spring框架 | SpringBoothtml
Spring Boot 提供了不少模板引擎的支持,例如 FreeMarker、Thymeleaf。這篇,咱們看下 Spring Boot 如何集成和使用 FreeMarker。git
Spring Boot 中使用 FreeMarker 模板很是簡單方便。若是想要使用FreeMarker 模板引擎,首先,修改 POM 文件,添加依賴。github
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-freemarker</artifactId>
- </dependency>
而後,咱們建立模板。值得注意的是,Spring Boot 集成的 FreeMarker 默認的配置文件放在 classpath:/templates/。所以,咱們須要在 src/main/resources/templates/ 添加模板文件。web
例如,咱們添加一個模板文件,叫作 welcome.ftl。spring
- <!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 麼,咱們來回顧下。springboot
- @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 對外提供服務。頁面的交互,交給前端作渲染。app
這種狀況下,是否是 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盤,是否生成文件了呢?
(完)相關示例完整代碼: springboot-action
靜態頁面生成器: freemarker-utils