SpringBoot 之Thymeleaf模板.


一、前言

    Thymeleaf 的出現是為了取代 JSP,雖然 JSP 存在了很長時間,並在 Java Web 開發中無處不在,但是它也存在一些缺陷:

1、JSP 最明顯的問題在於它看起來像HTML或XML,但它其實上並不是。大多數的JSP模板都是采用HTML的形式,但是又摻雜上了各種JSP標簽庫的標簽,使其變得很混亂。

2、JSP 規范是與 Servlet 規范緊密耦合的。這意味着它只能用在基於 Servlet 的Web應用之中。JSP模板不能作為通用的模板(如格式化Email),也不能用於非Servlet的 Web 應用。

    相較於 JSP 來說,Thymeleaf 很好的解決了這些缺點:

1、Thymeleaf模板是原生的,不依賴於標簽庫。它能在接受原始 HTML 的地方進行編輯和渲染。

2、因為它沒有與Servlet規范耦合,因此 Thymeleaf 模板能夠進入JSP所無法涉足的領域。這意味着Thymeleaf模板與JSP不同,它能夠按照原始的方式進行編輯甚至渲染,而不必經過任何類型的處理器。當然,我們需要Thymeleaf來處理模板並渲染得到最終期望的輸出。即便如此,如果沒有任何特殊的處理,home.html也能夠加載到Web瀏覽器中,並且看上去與完整渲染的效果很類似。

    Spring boot不建議使用 JSP 開發web。

二、集成 Thymeleaf 模板引擎

    SpringBoot 對 Thymeleaf 模板引擎的支持也很簡單:

    1、pom.xml

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

這時候,SpringBoot 對 Thymeleaf 模板的支持就完成了,我們就能在 Web 開發中使用 Thymeleaf 模板了,簡單吧?

之前的文章有提到 SpringBoot 的關鍵是 “約定俗成”。既然我們選擇了這么簡單的配置,那么在開發中就要遵守 SpringBoot 對 Thymeleaf 約定俗成的方案,最重要的一點就是 模板文件放在 templates 目錄下,即模板解析器前綴是 /templates/ ,后綴是 .html 。

    2、application.yml

    如果不想要所謂約定俗成的方案,想進行一些自定義的配置呢?且看下方:

spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    servlet:
      content-type: text/html
    enabled: true
    encoding: UTF-8
    mode: HTML5
    cache: false

    3、WebConfig.java

    如果上面的配置還不能達到你的要求,你想要更細化對 Thymeleaf 的控制,包括配置視圖解析器、模板解析器以及模板引擎這些,那么請看下面的方案!

/**
 * 1、ThymeleafViewResolver 接收邏輯視圖名稱將它解析為視圖
 * 2、SpringTemplateEngine會在Spring中啟用Thymeleaf引擎,用來解析模板,並基於這些模板渲染結果
 * 3、TemplateResolver會最終定位和查找模板。
 */
@Configuration
public class WebConfig {
    
    /**
     * 配置 Thymeleaf 視圖解析器 —— 將邏輯視圖名稱解析為 Thymeleaf 模板視圖
     *
     * @param springTemplateEngine 模板引擎
     * @return
     */
    @Bean
    public ViewResolver viewResolver(SpringTemplateEngine springTemplateEngine){
        ThymeleafViewResolver resolver = new ThymeleafViewResolver();
        resolver.setTemplateEngine(springTemplateEngine);
        return resolver;
    }

    /**
     * 模板引擎 —— 處理模板並渲染結果
     *
     * @param templateResolver 模板解析器
     * @return
     */
    @Bean
    public SpringTemplateEngine springTemplateEngine(ITemplateResolver templateResolver) {
        SpringTemplateEngine springTemplateEngine = new SpringTemplateEngine();
        springTemplateEngine.setTemplateResolver(templateResolver);
        return springTemplateEngine;
    }

    /**
     * 模板解析器 —— 加載 Thymeleaf 模板
     *
     * @return
     */
    @Bean
    public ITemplateResolver templateResolver() {
        SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
        templateResolver.setPrefix("classpath:/templates/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCacheable(false);
        templateResolver.setTemplateMode("HTML5");
        return templateResolver;
    }
}

三、使用 Thymeleaf 模板

    做好了上面的配置后,讓我們來看看如何在 SpringBoot 中使用 Thymeleaf 模板吧:

    1、模板文件 — /templates/user/list.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" />
    <title>Insert title here</title>
</head>
<body>
<h2>用戶列表</h2>
<div>
    <ul>
        <li  th:each="user:${users}">
            <span th:text="${user.uuid}"></span>-
            <span th:text="${user.name}"></span>-
            <span th:text="${user.age}"></span>-
            <span th:text="${user.address}"></span>
        </li>
    </ul>
</div>
</body>
</html>

    2、控制層 — ModelAndViews

    這里 Model 指的是:控制層處理完請求,返回需要渲染的結果;Views 指的是:模板的邏輯視圖名(前后端分離)。

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping("/list")
    public String listUser(Model model) {
        List<UserDto> userList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            userList.add(new UserDto(UUID.randomUUID().toString().replace("-", ""), "張三" + i, 1, "中國北京"));
        }
        model.addAttribute("users", userList);
        return "user/list";
    }
}

    3、效果

 

演示源代碼:https://github.com/JMCuixy/Thymeleaf

附錄:thymeleaf_3.0.5_中文參考手冊.pdf》— 鏈接:https://pan.baidu.com/s/1bYZJFKH8q1ONfd1gm-73tA 密碼:sady


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM