三、SpringBoot整合Thymeleaf視圖


3.1 Thymeleaf視圖介紹

先看下官網的介紹:
Thymeleaf是適用於Web和獨立環境的現代服務器端Java模板引擎。
Thymeleaf的主要目標是為您的開發工作流程帶來優雅的自然模板 -HTML可以在瀏覽器中正確顯示,也可以作為靜態原型工作,從而可以在開發團隊中加強協作。
Thymeleaf擁有適用於Spring Framework的模塊,與您喜歡的工具的大量集成以及插入您自己的功能的能力,對於現代HTML5 JVM Web開發而言,Thymeleaf是理想的選擇。

在SpringBoot中,SpringBoot對Thymeleaf提供了良好的支持,同時也提供了自動化配置,因此在SpringBoot中使用Thymeleaf非常快捷方便。

3.2 創建SpringBoot項目

創建方法建議使用IDEA快速創建SpringBoot項目,並選擇web、Thymeleaf依賴:
在這里插入圖片描述
創建完成后,IDEA自動在pom中加入了web和Thymeleaf依賴管理,pom.xml:

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

項目架構:
在這里插入圖片描述

3.2 配置Thymeleaf

SpringBoot為Thymeleaf提供了自動化配置類ThymeleafAutoConfiguration,源碼:

@Configuration
@EnableConfigurationProperties({ThymeleafProperties.class})
@ConditionalOnClass({TemplateMode.class, SpringTemplateEngine.class})
@AutoConfigureAfter({WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class})
public class ThymeleafAutoConfiguration {...}

可以看出相關的配置信息是從ThymeleafProperties類中獲得的,進一步查看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";
    //省略
}

從該配置可以看出默認的Thymeleaf存放位置是classpath:/templates/,即resources/templates/下,剛剛我們使用IDEA創建項目時,已經自動生成了該目錄。
我們如果需要對Thymeleaf的配置進行更改,可直接在application.properties中配置:

#是否開啟緩存,默認為true
spring.thymeleaf.cache=false
#檢查模板文件是否存在
spring.thymeleaf.check-template=true
#檢查模本目錄是否存在
spring.thymeleaf.check-template-location=true
#模板文件編碼
spring.thymeleaf.encoding=UTF-8
#模板位置
spring.thymeleaf.prefix=classpath:/templates/
#模板文件后綴名
spring.thymeleaf.suffix=.html
#Content-type
spring.thymeleaf.servlet.content-type=text/html

3.3 編寫Demo

1、新建User和UserController:
User.java:

package com.gongsir.springboot02.pojo;

public class User {
    private String name;
    private String major;
    private String grade;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

UserController.java:

@Controller
public class UserController {
    @GetMapping(path = "/users")
    public ModelAndView getUsers(){
        List<User> list = new ArrayList<>();
        User u1 = new User();
        u1.setName("龔濤");
        u1.setMajor("計算機");
        u1.setGrade("2017");
        list.add(u1);
        User u2 = new User();
        u2.setName("李詩雅");
        u2.setMajor("網絡工程");
        u2.setGrade("2017");
        list.add(u2);
        //視圖模板文件的名字,需在template目錄下創建同名模板文件
        ModelAndView mv = new ModelAndView("users");
        mv.addObject("users",list);
        return mv;
    }
}

2、在模板目錄下新建users.html模板文件,顯示數據:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>用戶列表</title>
</head>
<body>
    <table border="1px sold black">
        <tr>
            <td>姓名</td>
            <td>專業</td>
            <td>年級</td>
        </tr>
        <tr th:each="user:${users}">
            <td th:text="${user.name}"></td>
            <td th:text="${user.major}"></td>
            <td th:text="${user.grade}"></td>
        </tr>
    </table>
</body>
</html>

3、啟動項目,訪問http://localhost:8080/users,如圖:
在這里插入圖片描述

3.4 小結

本文主要介紹SpringBoot整合Thymeleaf視圖技術,並給了一個簡單demo演示,想學習更多Thymeleaf知識?看官網吧:https://www.thymeleaf.org/.
不過當前流行前后端分離技術,大多數開發不需要在后端整合視圖技術,后端只需要提供接口即可,待續.....


免責聲明!

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



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