自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Spring Boot整合Thymeleaf完整Web案例

開發(fā) 前端
Thymeleaf 是一種模板語言。那模板語言或模板引擎是什么?常見的模板語言都包含以下幾個概念:數(shù)據(jù)(Data)、模板(Template)、模板引擎(Template Engine)和結(jié)果文檔(Result Documents)。

[[206610]]

Thymeleaf 是一種模板語言。那模板語言或模板引擎是什么?常見的模板語言都包含以下幾個概念:數(shù)據(jù)(Data)、模板(Template)、模板引擎(Template Engine)和結(jié)果文檔(Result Documents)。

  • 數(shù)據(jù) 數(shù)據(jù)是信息的表現(xiàn)形式和載體,可以是符號、文字、數(shù)字、語音、圖像、視頻等。數(shù)據(jù)和信息是不可分離的,數(shù)據(jù)是信息的表達,信息是數(shù)據(jù)的內(nèi)涵。數(shù)據(jù)本身沒有意義,數(shù)據(jù)只有對實體行為產(chǎn)生影響時才成為信息。
  • 模板 模板,是一個藍圖,即一個與類型無關(guān)的類。編譯器在使用模板時,會根據(jù)模板實參對模板進行實例化,得到一個與類型相關(guān)的類。
  • 模板引擎 模板引擎(這里特指用于Web開發(fā)的模板引擎)是為了使用戶界面與業(yè)務(wù)數(shù)據(jù)(內(nèi)容)分離而產(chǎn)生的,它可以生成特定格式的文檔,用于網(wǎng)站的模板引擎就會生成一個標(biāo)準(zhǔn)的HTML文檔。
  • 結(jié)果文檔 一種特定格式的文檔,比如用于網(wǎng)站的模板引擎就會生成一個標(biāo)準(zhǔn)的HTML文檔。

模板語言用途廣泛,常見的用途如下:

  • 頁面渲染
  • 文檔生成
  • 代碼生成
  • 所有 “數(shù)據(jù)+模板=文本” 的應(yīng)用場景

這里案例用途自然是 頁面渲染,下面在 Spring Boot 中整合 Thymeleaf 實現(xiàn)完整 Web 案例。

一、運行 chapter-2-spring-boot-quick-start

chapter-2-spring-boot-quick-start 工程用的是內(nèi)存式數(shù)據(jù)庫,不需要配置數(shù)據(jù)源。下載運行即可。

1. 下載工程

git clone 下載工程 springboot-learning-example ,項目地址見 GitHub:

https://github.com/JeffLi1993/springboot-learning-example,即:

  1. git clone https://github.com/JeffLi1993/springboot-learning-example.git 

2. 工程結(jié)構(gòu)

用 IDEA 打開工程,可以看到子工程 chapter-2-spring-boot-quick-start ,其目錄如下:

  1. ├── pom.xml 
  2.  
  3. └── src 
  4.  
  5.    ├── main 
  6.  
  7.    │   ├── java 
  8.  
  9.    │   │   └── spring 
  10.  
  11.    │   │       └── boot 
  12.  
  13.    │   │           └── core 
  14.  
  15.    │   │               ├── QuickStartApplication.java 
  16.  
  17.    │   │               ├── domain 
  18.  
  19.    │   │               │   ├── User.java 
  20.  
  21.    │   │               │   └── UserRepository.java 
  22.  
  23.    │   │               ├── service 
  24.  
  25.    │   │               │   ├── UserService.java 
  26.  
  27.    │   │               │   └── impl 
  28.  
  29.    │   │               │       └── UserServiceImpl.java 
  30.  
  31.    │   │               └── web 
  32.  
  33.    │   │                   └── UserController.java 
  34.  
  35.    │   └── resources 
  36.  
  37.    │       ├── application.properties 
  38.  
  39.    │       ├── static 
  40.  
  41.    │       │   ├── css 
  42.  
  43.    │       │   │   └── default.css 
  44.  
  45.    │       │   └── images 
  46.  
  47.    │       │       └── favicon.ico 
  48.  
  49.    │       └── templates 
  50.  
  51.    │           ├── userForm.html 
  52.  
  53.    │           └── userList.html 
  54.  
  55.    └── test 
  56.  
  57.        └── java 
  58.  
  59.            └── spring 
  60.  
  61.                └── boot 
  62.  
  63.                    └── core 
  64.  
  65.                        ├── QuickStartApplicationTests.java 
  66.  
  67.                        └── domain 
  68.  
  69.                            └── UserRepositoryTests.java 

對應(yīng)目錄:

  • org.spring.springboot.controller - Controller 層
  • org.spring.springboot.dao - 數(shù)據(jù)操作層 DAO
  • org.spring.springboot.domain - 實體類
  • org.spring.springboot.service - 業(yè)務(wù)邏輯層
  • Application - 應(yīng)用啟動類
  • application.properties - 應(yīng)用配置文件

模板是會用到下面兩個目錄

  • static 目錄是存放 CSS、JS 等資源文件
  • templates 目錄是存放視圖

3. 編譯運行工程

在該工程根目錄,運行 maven 指令進行編譯:

  1. cd chapter-2-spring-boot-quick-start  
  2. mvn clean install 

編譯工程成功后,右鍵運行名為 QuickStartApplication.java 應(yīng)用啟動類的 main 函數(shù),然后瀏覽器訪問 localhost:8080/users 即可: 用戶列表頁面:


用戶編輯頁面:

二、詳解 chapter-2-spring-boot-quick-start

工程代碼:

1. pom.xml Thymeleaf 依賴

使用模板引擎,就在 pom.xml 加入 Thymeleaf 組件依賴:

  1. <!-- 模板引擎 Thymeleaf 依賴 -->  
  2. <dependency> 
  3.    <groupId>org.springframework.boot</groupId> 
  4.    <artifactId>spring-boot-starter-thymeleaf</artifactId> 
  5. </dependency> 

Thymeleaf 是什么? Thymeleaf is a modern server-side Java template engine for both web and standalone environments.

Thymeleaf's main goal is to bring elegant natural templates to your development workflow — HTML that can be correctly displayed in browsers and also work as static prototypes, allowing for stronger collaboration in development teams.

Thymeleaf 是新一代 Java 模板引擎,在 Spring 4 后推薦使用。

整體個 pom.xml 配置如下:

  1. <?xml version="1.0" encoding="UTF-8"?> 
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  3.         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
  4.    <modelVersion>4.0.0</modelVersion> 
  5.  
  6.    <groupId>spring.boot.core</groupId> 
  7.    <artifactId>chapter-2-spring-boot-quick-start</artifactId> 
  8.    <version>0.0.1-SNAPSHOT</version> 
  9.    <packaging>jar</packaging> 
  10.    <name>chapter-2-spring-boot-quick-start</name
  11.    <description>第二章快速入門案例</description> 
  12.  
  13.    <parent> 
  14.        <groupId>org.springframework.boot</groupId> 
  15.        <artifactId>spring-boot-starter-parent</artifactId> 
  16.        <version>1.5.7.RELEASE</version> 
  17.    </parent> 
  18.  
  19.    <properties> 
  20.        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
  21.        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
  22.        <java.version>1.8</java.version>
  23.    </properties> 
  24.  
  25.    <dependencies> 
  26.  
  27.        <!-- Web 依賴 --> 
  28.        <dependency> 
  29.            <groupId>org.springframework.boot</groupId> 
  30.            <artifactId>spring-boot-starter-web</artifactId> 
  31.        </dependency> 
  32.  
  33.        <!-- 單元測試依賴 --> 
  34.        <dependency> 
  35.            <groupId>org.springframework.boot</groupId> 
  36.            <artifactId>spring-boot-starter-test</artifactId> 
  37.            <scope>test</scope> 
  38.        </dependency> 
  39.  
  40.        <!-- Spring Data JPA 依賴 :: 數(shù)據(jù)持久層框架 --> 
  41.        <dependency> 
  42.            <groupId>org.springframework.boot</groupId> 
  43.            <artifactId>spring-boot-starter-data-jpa</artifactId> 
  44.        </dependency> 
  45.  
  46.        <!-- h2 數(shù)據(jù)源連接驅(qū)動 --> 
  47.        <dependency> 
  48.            <groupId>com.h2database</groupId> 
  49.            <artifactId>h2</artifactId> 
  50.            <scope>runtime</scope> 
  51.        </dependency> 
  52.  
  53.        <!-- 模板引擎 Thymeleaf 依賴 --> 
  54.        <dependency> 
  55.            <groupId>org.springframework.boot</groupId> 
  56.            <artifactId>spring-boot-starter-thymeleaf</artifactId> 
  57.        </dependency> 
  58.    </dependencies> 
  59.  
  60.    <build> 
  61.        <plugins> 
  62.            <!-- Spring Boot Maven 插件 --> 
  63.            <plugin> 
  64.                <groupId>org.springframework.boot</groupId> 
  65.                <artifactId>spring-boot-maven-plugin</artifactId> 
  66.            </plugin> 
  67.        </plugins> 
  68.    </build> 
  69.  
  70. </project> 

2. Thymeleaf 依賴配置

在 Spring Boot 項目中加入 Thymeleaf 依賴,即可啟動其默認配置。如果想要自定義配置,可以在 application.properties 配置如下:

  1. spring.thymeleaf.cache=true # Enable template caching. 
  2. spring.thymeleaf.check-template=true # Check that the template exists before rendering it. 
  3. spring.thymeleaf.check-template-location=true # Check that the templates location exists. 
  4. spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks. 
  5. spring.thymeleaf.encoding=UTF-8 # Template files encoding. 
  6. spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution. 
  7. spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers. 
  8. spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL. 
  9. spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes. 
  10. spring.thymeleaf.reactive.media-types= # Media types supported by the view technology. 
  11. spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses. 
  12. spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL. 
  13. spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. 
  14. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved. 

3. Thymeleaf 使用

Controller 如何將 View 指向 Thymeleaf

用戶控制層代碼如下:

  1. @Controller 
  2. @RequestMapping(value = "/users")     // 通過這里配置使下面的映射都在 /users 
  3. public class UserController { 
  4.  
  5.    @Autowired 
  6.    UserService userService;          // 用戶服務(wù)層 
  7.  
  8.    /**
  9.     *  獲取用戶列表 
  10.     *    處理 "/users" 的 GET 請求,用來獲取用戶列表 
  11.     *    通過 @RequestParam 傳遞參數(shù),進一步實現(xiàn)條件查詢或者分頁查詢 
  12.     */ 
  13.    @RequestMapping(method = RequestMethod.GET) 
  14.    public String getUserList(ModelMap map) { 
  15.        map.addAttribute("userList", userService.findAll()); 
  16.        return "userList"
  17.    } 
  18.  
  19.    /** 
  20.     * 顯示創(chuàng)建用戶表單 
  21.     * 
  22.     */ 
  23.    @RequestMapping(value = "/create", method = RequestMethod.GET) 
  24.    public String createUserForm(ModelMap map) { 
  25.        map.addAttribute("user", new User()); 
  26.        map.addAttribute("action""create"); 
  27.        return "userForm"
  28.    } 
  29.  
  30.    /**
  31.     *  創(chuàng)建用戶 
  32.     *    處理 "/users" 的 POST 請求,用來獲取用戶列表 
  33.     *    通過 @ModelAttribute 綁定參數(shù),也通過 @RequestParam 從頁面中傳遞參數(shù) 
  34.     */ 
  35.    @RequestMapping(value = "/create", method = RequestMethod.POST) 
  36.    public String postUser(@ModelAttribute User user) { 
  37.        userService.insertByUser(user); 
  38.        return "redirect:/users/"
  39.    } 
  40.  
  41.    /** 
  42.     * 顯示需要更新用戶表單 
  43.     *    處理 "/users/{id}" 的 GET 請求,通過 URL 中的 id 值獲取 User 信息 
  44.     *    URL 中的 id ,通過 @PathVariable 綁定參數(shù) 
  45.     */ 
  46.    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET) 
  47.    public String getUser(@PathVariable Long id, ModelMap map) { 
  48.        map.addAttribute("user", userService.findById(id)); 
  49.        map.addAttribute("action""update"); 
  50.        return "userForm"
  51.    } 
  52.  
  53.    /** 
  54.     * 處理 "/users/{id}" 的 PUT 請求,用來更新 User 信息 
  55.     * 
  56.     */
  57.    @RequestMapping(value = "/update", method = RequestMethod.POST) 
  58.    public String putUser(@ModelAttribute User user) { 
  59.        userService.update(user); 
  60.        return "redirect:/users/"
  61.    } 
  62.  
  63.    /** 
  64.     * 處理 "/users/{id}" 的 GET 請求,用來刪除 User 信息 
  65.     */
  66.    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) 
  67.    public String deleteUser(@PathVariable Long id) { 
  68.  
  69.        userService.delete(id); 
  70.        return "redirect:/users/";
  71.    } 
  72.  

ModelMap 對象來進行數(shù)據(jù)綁定到視圖。return 字符串,該字符串對應(yīng)的目錄在 resources/templates 下的模板名字。 @ModelAttribute 注解是用來獲取頁面 Form 表單提交的數(shù)據(jù),并綁定到 User 數(shù)據(jù)對象。

Form 表單頁面

核心代碼:

  1. <form th:action="@{/users/{action}(action=${action})}" method="post" class="form-horizontal"
  2.  
  3.                <input type="hidden" name="id" th:value="${user.id}"/> 
  4.  
  5.                <div class="form-group"
  6.                    <label for="user_name" class="col-sm-2 control-label">名稱</label> 
  7.                    <div class="col-xs-4"
  8.                        <input type="text" class="form-control" id="user_name" name="name" th:value="${user.name}" /> 
  9.                    </div> 
  10.                </div> 
  11.  
  12.                <div class="form-group"
  13.  
  14.                    <label for="user_age" class="col-sm-2 control-label">年齡:</label> 
  15.                    <div class="col-xs-4"
  16.                       <input type="text" class="form-control" id="user_age" name="age" th:value="${user.age}"/> 
  17.                    </div> 
  18.                </div> 
  19.  
  20.                <div class="form-group"
  21.                    <label for="user_birthday" class="col-sm-2 control-label">出生日期:</label> 
  22.                    <div class="col-xs-4"
  23.                        <input type="date" class="form-control" id="user_birthday" name="birthday" th:value="${user.birthday}"/> 
  24.                    </div> 
  25.                </div> 
  26.  
  27.                <div class="form-group"
  28.                    <div class="col-sm-offset-2 col-sm-10"
  29.                        <input class="btn btn-primary" type="submit" value="提交"/>   
  30.                        <input class="btn" type="button" value="返回" onclick="history.back()"/> 
  31.                    </div> 
  32.                </div> 
  33.            </form> 

這里定義了一個 Form 表單用于新增或者更新用戶。

列表頁面

代碼如下:

  1. <table class="table table-hover table-condensed"
  2.                <legend> 
  3.                    <strong>用戶列表</strong> 
  4.                </legend> 
  5.                <thead> 
  6.                    <tr> 
  7.                        <th>用戶編號</th> 
  8.                        <th>名稱</th> 
  9.                        <th>年齡</th> 
  10.                        <th>出生時間</th> 
  11.                        <th>管理</th> 
  12.                    </tr> 
  13.                </thead> 
  14.                <tbody> 
  15.                    <tr th:each="user : ${userList}"
  16.                        <th scope="row" th:text="${user.id}"></th> 
  17.                        <td><a th:href="@{/users/update/{userId}(userId=${user.id})}" th:text="${user.name}"></a></td> 
  18.                        <td th:text="${user.age}"></td> 
  19.                        <td th:text="${user.birthday}"></td> 
  20.                        <td><a class="btn btn-danger" th:href="@{/users/delete/{userId}(userId=${user.id})}">刪除</a></td> 
  21.                    </tr> 
  22.                </tbody> 
  23.            </table

這里循環(huán)了用戶列表。

Tymeleaf 的語法糖

我這邊也就不詳細展開了,大家看看人家寫的 http://www.cnblogs.com/nuoyiamy/p/5591559.html 或者看看官方文檔 http://www.thymeleaf.org/documentation.html

三、本文小結(jié)

該文,利用 Thymeleaf 做了個 Web 的 CRUD 案例。大家多指教~

【本文為51CTO專欄作者“李強強”的原創(chuàng)稿件,轉(zhuǎn)載請通過51CTO聯(lián)系作者獲取授權(quán)】

戳這里,看該作者更多好文

責(zé)任編輯:武曉燕 來源: 51CTO專欄
相關(guān)推薦

2017-05-12 15:47:15

Spring BootMybatis Ann Web

2024-01-16 08:17:29

Mybatis驗證業(yè)務(wù)

2022-12-23 08:28:42

策略模式算法

2022-07-21 11:04:53

Swagger3Spring

2017-04-17 10:35:40

Spring BooRedis 操作

2017-08-02 14:44:06

Spring Boot開發(fā)注解

2023-11-02 18:01:24

SpringMVC配置

2022-05-06 10:42:09

JavaFlowable引擎

2024-03-26 08:08:08

SpringBPMN模型

2024-11-11 10:02:37

Spring搜索數(shù)據(jù)

2025-03-26 03:25:00

SpringGuavaCaffeine

2022-05-18 12:04:19

Mybatis數(shù)據(jù)源Spring

2021-01-11 13:46:26

Spring BootThymeleafJava

2019-02-21 10:38:10

Web 開發(fā)代碼

2017-05-19 14:47:24

Spring Boot Elasticsea場景

2019-08-15 10:56:10

WebServletSpring mvc

2018-05-04 15:27:22

Spring Boo Web開發(fā)

2022-03-18 09:00:00

開發(fā)Web服務(wù)應(yīng)用程序

2020-08-19 08:55:47

Redis緩存數(shù)據(jù)庫

2022-08-24 08:42:59

Minio存儲Golang
點贊
收藏

51CTO技術(shù)棧公眾號