springboot freeMarker

發表於  | Spring框架 | SpringBoothtml

Spring Boot 提供了不少模板引擎的支持,例如 FreeMarker、Thymeleaf。這篇,咱們看下 Spring Boot 如何集成和使用 FreeMarker。git

Spring Boot 中使用 FreeMarker 模板很是簡單方便。若是想要使用FreeMarker 模板引擎,首先,修改 POM 文件,添加依賴。github

FreeMaker 代替 JSP 做爲頁面渲染

  
  
  
  
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-freemarker</artifactId>
  4. </dependency>

而後,咱們建立模板。值得注意的是,Spring Boot 集成的 FreeMarker 默認的配置文件放在 classpath:/templates/。所以,咱們須要在 src/main/resources/templates/ 添加模板文件。web

例如,咱們添加一個模板文件,叫作 welcome.ftl。spring

  
  
  
  
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <body>
  4. Date: ${time?date}<br>
  5. Message: ${message}
  6. </body>
  7. </html>

那麼,最後一步,咱們在控制類中只須要這麼配置就能夠了。後端

  
  
  
  
  1. @Controller("template.freemarkerController")
  2. public class WelcomeController {
  3. @RequestMapping("/template/freemarker/welcome")
  4. public String welcome(Map<String, Object> model) {
  5. model.put("time", new Date());
  6. model.put("message", "梁桂釗");
  7. return "welcome";
  8. }
  9. }

還記得咱們以前的 WebMain 麼,咱們來回顧下。springboot

  
  
  
  
  1. @RestController
  2. @EnableAutoConfiguration
  3. @ComponentScan(basePackages = { "com.lianggzone.springboot" })
  4. public class WebMain {
  5. public static void main(String[] args) throws Exception {
  6. SpringApplication.run(WebMain.class, args);
  7. }
  8. }

直接運行 WebMain 類,或者能夠經過「mvn spring-boot:run」在命令行啓動該應用。會啓動一個內嵌的 Tomcat 服務器運行在 8080 端口。訪問 「http://localhost:8080/template/freemarker/welcome」 能夠看到頁面上顯示結果。服務器

生成靜態文件

上面的場景,是很是典型的 MVC 的使用場景,咱們經過 FreeMaker 代替 JSP 做爲頁面渲染。可是,隨着,先後端分離,JSP 漸漸遠離咱們的視野,服務端更多地處理業務邏輯,經過 RESTful 或者 RPC 對外提供服務。頁面的交互,交給前端作渲染。app

這種狀況下,是否是 FreeMarker 就沒有用武之地了呢?實際上,FreeMarker 做爲模板引擎,還有不少使用場景,例如,咱們能夠把咱們能夠動靜分離,把相對不會變化的內容經過 FreeMarker 渲染生成靜態文件上傳到內容服務,內容服務經過 CDN 進行資源分發。

那麼,咱們對上面的代碼進行一個小改造,模擬一個文件生成到本地的場景。

  
  
  
  
  1. @RestController("template.freemarkerController2")
  2. @EnableAutoConfiguration
  3. public class Welcome2Controller {
  4. @Autowired
  5. private Configuration configuration;
  6. @RequestMapping("/template/freemarker/welcome2")
  7. public String welcome2(Map model ) throws Exception {
  8. model . put ( "time" , new Date ());
  9. model . put ( "message" , "梁桂釗" );
  10. Template template = configuration . getTemplate ( "welcome.ftl" );
  11. String content = FreeMarkerTemplateUtils . processTemplateIntoString ( template , model );
  12. FileUtils . writeStringToFile ( new File ( "d:/welcome.html" ), content );
  13. return "welcome" ;
  14. }
  15. }

直接運行 WebMain 類,訪問 「http://localhost:8080/template/freemarker/welcome2」 能夠看到頁面上顯示結果,並查看D盤,是否生成文件了呢?

擴展閱讀

源代碼

相關示例完整代碼: springboot-action
靜態頁面生成器: freemarker-utils

(完)
相關文章
相關標籤/搜索