手摸手,一起重溫SpringBoot 2知識點(三)整合視圖層技術之Freemarker

來自官網的簡介

FreeMarker 是一款 模板引擎: 即一種基於模板和要改變的數據, 並用來生成輸出文本(HTML網頁,電子郵件,配置文件,源代碼等)的通用工具。 它不是面向最終用戶的,而是一個Java類庫,是一款程序員可以嵌入他們所開發產品的組件。

模板編寫爲FreeMarker Template Language (FTL)。它是簡單的,專用的語言, 不是 像PHP那樣成熟的編程語言。 那就意味着要準備數據在真實編程語言中來顯示,比如數據庫查詢和業務運算, 之後模板顯示已經準備好的數據。在模板中,你可以專注於如何展現數據, 而在模板之外可以專注於要展示什麼數據。

overview

這種方式通常被稱爲 MVC (模型 視圖 控制器) 模式,對於動態網頁來說,是一種特別流行的模式。 它幫助從開發人員(Java 程序員)中分離出網頁設計師(HTML設計師)。設計師無需面對模板中的複雜邏輯, 在沒有程序員來修改或重新編譯代碼時,也可以修改頁面的樣式。

而FreeMarker最初的設計,是被用來在MVC模式的Web開發框架中生成HTML頁面的,它沒有被綁定到 Servlet或HTML或任意Web相關的東西上。它也可以用於非Web應用環境中。

FreeMarker 是 免費的, 基於Apache許可證2.0版本發佈。

一、創建項目

  1. 首先創建一個 Spring Boot 工程,引入 Freemarker 依賴

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.7.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.junya</groupId>
        <artifactId>freemarker</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>freemarker</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-freemarker</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
                <exclusions>
                    <exclusion>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
  2. 新建User實體類,此處用了lombok的@Data註解,可以自動給我們生成setter、getter、equals等方法。

    package com.junya.freemarker.entity;
    
    import lombok.Data;
    
    /**
     * @author ZHANGCHAO
     * @date 2020/5/14 15:16
     * @since 1.0.0
     */
    @Data
    public class User {
    
        private Long id;
        private String userName;
        private String address;
        private Integer gender;
    }
    
  3. 新建UserController類,增加user方法,返回視圖名爲user

    package com.junya.freemarker.controller;
    
    import com.junya.freemarker.entity.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.GetMapping;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    
    /**
     * @author ZHANGCHAO
     * @date 2020/5/14 15:21
     * @since 1.0.0
     */
    @Controller
    public class UserController {
    
      @GetMapping("/user")
      public String user(Model model) {
        List<User> userList = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
          User user = new User();
          user.setId((long) i);
          user.setUserName("mayanhong - " + i);
          user.setAddress("www.baidu.com - " + i);
          user.setGender(random.nextInt(3)); // 0 男 1 女 其他未知
          userList.add(user);
        }
        model.addAttribute("users", userList);
        return "user";
      }
    }
    
  4. 在resources下的templates下新建user.ftl視圖模版

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>user</title>
    </head>
    <body>
    <table border="1">
        <tr>
            <td>編號</td>
            <td>用戶名</td>
            <td>地址</td>
            <td>性別-if</td>
            <td>性別-switch</td>
        </tr>
        <#list users as user>
            <tr>
                <td>${user.id}</td>
                <td>${user.userName}</td>
                <td>${user.address}</td>
                <#-- 演示if用法 -->
                <td>
                    <#if user.gender==0>
                        男
                    <#elseif user.gender==1>
                        女
                    <#else>
                        未知
                    </#if>
                </td>
                <#-- 演示switch用法 -->
                <td>
                    <#switch user.gender>
                        <#case 0><#break>
                        <#case 1><#break>
                        <#default >不知道
                    </#switch>
                </td>
            </tr>
        </#list>
    </table>
    </body>
    </html>
    

二、啓動測試

啓動項目,訪問http://localhost:8080/user,發現報500錯誤:

TIM截圖20200514153910

TIM圖片20200514154019

查看源碼,發現SpringBoot 2.2以後默認的Freemarker後綴已改爲.ftlh,如下:

TIM圖片20200514154244

在application.properties中加個配置:

spring.freemarker.suffix=.ftl

重新啓動項目,訪問http://localhost:8080/user

TIM圖片20200514162345

ok,一切正常了!頁面已經渲染出數據!

三、其他配置

我們還可以在 application.properties 中進行自定義配置,如默認模版位置等:

spring.freemarker.allow-request-override=false
spring.freemarker.allow-session-override=false
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=false
spring.freemarker.expose-session-attributes=false
spring.freemarker.suffix=.ftl
spring.freemarker.template-loader-path=classpath:/templates/
  1. HttpServletRequest的屬性是否可以覆蓋controller中model的同名項
  2. HttpSession的屬性是否可以覆蓋controller中model的同名項
  3. 是否開啓緩存
  4. 模板文件編碼
  5. 是否檢查模板位置
  6. Content-Type的值
  7. 是否將HttpServletRequest中的屬性添加到Model中
  8. 是否將HttpSession中的屬性添加到Model中
  9. 模板文件後綴
  10. 模板文件位置
總結

在SpringBoot中整合Freemarker與以前的SSM相比還是非常簡單的,因爲SpringBoot已經默認給我們整合了很多配置,我們只需要簡單修改下就可以了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章