開發與維運

江帥帥:精通 Spring Boot 系列 04

  1. Web 開發的支持

使用 Spring Boot 實現 Web 開發更加便捷了,因為直接依賴 spring-boot-starter-web 模塊即可支持 Web 開發,此模塊預定義了 Web 開發中常用的依賴包,還有內嵌的 Tomcat 作為默認 Web 容器。

  1. Thymeleaf 模板引擎
    目前,多數企業級應用開發中都支持前後端分離,但還有少數離不開視圖層技術,Spring Boot 提供了很多模板引擎來支持視圖層技術,比如 Thymeleaf、Freemarker、Velocity。

Thymeleaf 是官方推薦使用的新一代 Java 模板引擎,並支持 HTML 原型,模板表達式在脫離運行環境下不汙染 HTML 結構,能讓前端直接通過瀏覽器查看基本樣式,也能讓後端使用真實數據查看展示效果。

  1. 整合使用 Thymeleaf 模板
    3.1. 創建工程

創建一個 Spring Boot 工程,編輯 pom.xml 文件,添加 web 和 thymeleaf 依賴。另外,App 啟動類與之前一致。


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>


<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

3.2. 添加視圖文件
在 src/main/resources/templates 目錄下,新建 nicebook.html 文件。

<head>
    <meta charset="UTF-8">
    <title>良心好書</title>
</head>
<body>
    <table border="1">
        <tr>
            <td>序號</td>
            <td>好書</td>
            <td>作者</td>
        </tr>
        <tr th:each="book:${books}">
            <td th:text="${book.id}"></td>
            <td th:text="${book.name}"></td>
            <td th:text="${book.author}"></td>
        </tr>
    </table>
</body>

3.3. 配置 Thymeleaf
如果想自定義 Thymeleaf 配置參數,可以在 application.properties 文件中進行配置,常見的配置選項如下:

模板文件存放位置

spring.thymeleaf.prefix=classpath:/templates/

是否開啟緩存,默認為 true,開發時可設置為 false

spring.thymeleaf.cache=true

檢查模板位置是否存在,默認為 true

spring.thymeleaf.check-template-location=true

檢查模板是否存在,默認為 true

spring.thymeleaf.check-template=true

模板文件後綴設置

spring.thymeleaf.suffix=.html

模板文件編碼設置

spring.thymeleaf.encoding=UTF-8

Content-Type 配置

spring.thymeleaf.servlet.content-type=text/html

3.4. 創建 POJO
public class Book {

private Integer id;
private String name;
private String author;

// getter 和 setter 方法

}

3.5. 創建 BookController 控制器
@Controller
public class BookController {

@GetMapping("/books")
public ModelAndView books() {

    List<Book> bookList = new ArrayList<>()

    Book book1 = new Book();
    book1.setId(1);
    book1.setName("《碼農翻身:用故事給技術加點料》");
    book1.setAuthor("劉欣");

    Book book2 = new Book();
    book2.setId(2);
    book2.setName("《漫畫算法:小灰的算法之旅(全綵)》");
    book2.setAuthor("魏夢舒");

    bookList.add(book1);
    bookList.add(book2);

    ModelAndView mv = new ModelAndView();
    mv.addObject("bookList");
    mv.setViewName("nicebook");
    return mv;
}

}

3.6. 運行測試
瀏覽器中訪問:http://localhost:8080/books,即可看到如下頁面。

1.png

  1. Thymeleaf 的支持
    Spring Boot 通過 org.springframework.boot.autoconfigure.thymeleaf 包為 Thymeleaf 提供了自動配置,涉及到的類如下:

2.png

其中 ThymeleafAutoConfiguration 和 ThymeleafProperties 類是比較重要的,前者對集成所需要的 Bean 進行自動配置,後者主要讀取 application.properties 配置文件,可自定義 Thymeleaf 的屬性和默認配置。

ThymeleafProperties 類部分源碼如下:

@ConfigurationProperties(

prefix = "spring.thymeleaf"

)
public class ThymeleafProperties {

private static final Charset DEFAULT_ENCODING;
public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";
private boolean checkTemplate = true;
private boolean checkTemplateLocation = true;
private String prefix = "classpath:/templates/";
private String suffix = ".html";
private String mode = "HTML";
private Charset encoding;
private boolean cache;
private Integer templateResolverOrder;
private String[] viewNames;
private String[] excludedViewNames;
private boolean enableSpringElCompiler;
private boolean renderHiddenMarkersBeforeCheckboxes;
private boolean enabled;
private final ThymeleafProperties.Servlet servlet;
private final ThymeleafProperties.Reactive reactive;

...   

}

  1. 拓展:Thymeleaf 常用語法
    5.1. 使用 URL

通過 @{…} 來處理常見 URL。

http://www.naixuejiaoyu.com}">奈學教育

奈學教育

奈學教育

5.2. 使用表達式
主要用來從模板中的 WebContext 獲取param、request、session 和 application 中的屬性。使用 ${x} 即可返回存儲在 Thymeleaf 上下文中的變量 x 或作為 request 作用域中的屬性。

${param.x} 能夠返回名為 x 的請求參數;
${session.x} 能夠返回名為 x 的 HttpSession 作用域中的屬性;
${application.x} 能夠返回名為 x 的 ServletContext 作用域中的屬性。

5.3. 使用字符串
如果需要對一段文字中的某一處進行替換,可以使用 |…| 這種便捷方式,但不能包含其他常量、條件表達式,只能包含變量表達式 x即可返回存儲在Thymeleaf上下文中的變量x或作為request作用域中的屬性。¨G7G¨K25K如果需要對一段文字中的某一處進行替換,可以使用∣…∣這種便捷方式,但不能包含其他常量、條件表達式,只能包含變量表達式{…},有一定侷限性。

5.4. 使用運算符
平時看到的算術運算符和邏輯運算符都可以使用。

5.5. 使用條件判斷
可以使用 th:if 和 th:unless 屬性進行條件判斷,前者條件成立時顯示,後者不成立時才顯示。也可以使用 Switch 結構,默認選項使用 * 來表示。

奈學教育

<p th:case="'Java'">Java 從入門到逃難</p>
<p th:case="'Python'">Python 從入門到逃難</p>

5.6. 使用循環
使用 th:each 即可實現循環。

<td th:text="${book.id}"></td>
<td th:text="${book.name}"></td>
<td th:text="${book.author}"></td>

5.7. 使用內置對象
通過 # 可以直接訪問 Thymeleaf 的內置對象。

dates:日期

calendars:日曆

numbers:數值格式化

strings:字符串格式化

objects:對象

maps:Map 操作工具

aggregates:操作數組或集合的工具

bools:布爾

sets:Set 操作工具

messages:消息

arrays:Array 操作工具

lists:List 操作工具

來源於:奈學開發者社區-江帥帥

Leave a Reply

Your email address will not be published. Required fields are marked *