Spring Boot整合Thymeleaf完整Web案例
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,即:
- git clone https://github.com/JeffLi1993/springboot-learning-example.git
2. 工程結(jié)構(gòu)
用 IDEA 打開工程,可以看到子工程 chapter-2-spring-boot-quick-start ,其目錄如下:
- ├── pom.xml
- └── src
- ├── main
- │ ├── java
- │ │ └── spring
- │ │ └── boot
- │ │ └── core
- │ │ ├── QuickStartApplication.java
- │ │ ├── domain
- │ │ │ ├── User.java
- │ │ │ └── UserRepository.java
- │ │ ├── service
- │ │ │ ├── UserService.java
- │ │ │ └── impl
- │ │ │ └── UserServiceImpl.java
- │ │ └── web
- │ │ └── UserController.java
- │ └── resources
- │ ├── application.properties
- │ ├── static
- │ │ ├── css
- │ │ │ └── default.css
- │ │ └── images
- │ │ └── favicon.ico
- │ └── templates
- │ ├── userForm.html
- │ └── userList.html
- └── test
- └── java
- └── spring
- └── boot
- └── core
- ├── QuickStartApplicationTests.java
- └── domain
- └── 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 指令進行編譯:
- cd chapter-2-spring-boot-quick-start
- 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 組件依賴:
- <!-- 模板引擎 Thymeleaf 依賴 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </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 配置如下:
- <?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>spring.boot.core</groupId>
- <artifactId>chapter-2-spring-boot-quick-start</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <name>chapter-2-spring-boot-quick-start</name>
- <description>第二章快速入門案例</description>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.5.7.RELEASE</version>
- </parent>
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
- <dependencies>
- <!-- Web 依賴 -->
- <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>
- <!-- Spring Data JPA 依賴 :: 數(shù)據(jù)持久層框架 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
- <!-- h2 數(shù)據(jù)源連接驅(qū)動 -->
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <scope>runtime</scope>
- </dependency>
- <!-- 模板引擎 Thymeleaf 依賴 -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-thymeleaf</artifactId>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <!-- Spring Boot Maven 插件 -->
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
2. Thymeleaf 依賴配置
在 Spring Boot 項目中加入 Thymeleaf 依賴,即可啟動其默認配置。如果想要自定義配置,可以在 application.properties 配置如下:
- spring.thymeleaf.cache=true # Enable template caching.
- spring.thymeleaf.check-template=true # Check that the template exists before rendering it.
- spring.thymeleaf.check-template-location=true # Check that the templates location exists.
- spring.thymeleaf.enabled=true # Enable Thymeleaf view resolution for Web frameworks.
- spring.thymeleaf.encoding=UTF-8 # Template files encoding.
- spring.thymeleaf.excluded-view-names= # Comma-separated list of view names that should be excluded from resolution.
- spring.thymeleaf.mode=HTML5 # Template mode to be applied to templates. See also StandardTemplateModeHandlers.
- spring.thymeleaf.prefix=classpath:/templates/ # Prefix that gets prepended to view names when building a URL.
- spring.thymeleaf.reactive.max-chunk-size= # Maximum size of data buffers used for writing to the response, in bytes.
- spring.thymeleaf.reactive.media-types= # Media types supported by the view technology.
- spring.thymeleaf.servlet.content-type=text/html # Content-Type value written to HTTP responses.
- spring.thymeleaf.suffix=.html # Suffix that gets appended to view names when building a URL.
- spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain.
- spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
3. Thymeleaf 使用
Controller 如何將 View 指向 Thymeleaf
用戶控制層代碼如下:
- @Controller
- @RequestMapping(value = "/users") // 通過這里配置使下面的映射都在 /users
- public class UserController {
- @Autowired
- UserService userService; // 用戶服務(wù)層
- /**
- * 獲取用戶列表
- * 處理 "/users" 的 GET 請求,用來獲取用戶列表
- * 通過 @RequestParam 傳遞參數(shù),進一步實現(xiàn)條件查詢或者分頁查詢
- */
- @RequestMapping(method = RequestMethod.GET)
- public String getUserList(ModelMap map) {
- map.addAttribute("userList", userService.findAll());
- return "userList";
- }
- /**
- * 顯示創(chuàng)建用戶表單
- *
- */
- @RequestMapping(value = "/create", method = RequestMethod.GET)
- public String createUserForm(ModelMap map) {
- map.addAttribute("user", new User());
- map.addAttribute("action", "create");
- return "userForm";
- }
- /**
- * 創(chuàng)建用戶
- * 處理 "/users" 的 POST 請求,用來獲取用戶列表
- * 通過 @ModelAttribute 綁定參數(shù),也通過 @RequestParam 從頁面中傳遞參數(shù)
- */
- @RequestMapping(value = "/create", method = RequestMethod.POST)
- public String postUser(@ModelAttribute User user) {
- userService.insertByUser(user);
- return "redirect:/users/";
- }
- /**
- * 顯示需要更新用戶表單
- * 處理 "/users/{id}" 的 GET 請求,通過 URL 中的 id 值獲取 User 信息
- * URL 中的 id ,通過 @PathVariable 綁定參數(shù)
- */
- @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
- public String getUser(@PathVariable Long id, ModelMap map) {
- map.addAttribute("user", userService.findById(id));
- map.addAttribute("action", "update");
- return "userForm";
- }
- /**
- * 處理 "/users/{id}" 的 PUT 請求,用來更新 User 信息
- *
- */
- @RequestMapping(value = "/update", method = RequestMethod.POST)
- public String putUser(@ModelAttribute User user) {
- userService.update(user);
- return "redirect:/users/";
- }
- /**
- * 處理 "/users/{id}" 的 GET 請求,用來刪除 User 信息
- */
- @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
- public String deleteUser(@PathVariable Long id) {
- userService.delete(id);
- return "redirect:/users/";
- }
- }
ModelMap 對象來進行數(shù)據(jù)綁定到視圖。return 字符串,該字符串對應(yīng)的目錄在 resources/templates 下的模板名字。 @ModelAttribute 注解是用來獲取頁面 Form 表單提交的數(shù)據(jù),并綁定到 User 數(shù)據(jù)對象。
Form 表單頁面
核心代碼:
- <form th:action="@{/users/{action}(action=${action})}" method="post" class="form-horizontal">
- <input type="hidden" name="id" th:value="${user.id}"/>
- <div class="form-group">
- <label for="user_name" class="col-sm-2 control-label">名稱</label>
- <div class="col-xs-4">
- <input type="text" class="form-control" id="user_name" name="name" th:value="${user.name}" />
- </div>
- </div>
- <div class="form-group">
- <label for="user_age" class="col-sm-2 control-label">年齡:</label>
- <div class="col-xs-4">
- <input type="text" class="form-control" id="user_age" name="age" th:value="${user.age}"/>
- </div>
- </div>
- <div class="form-group">
- <label for="user_birthday" class="col-sm-2 control-label">出生日期:</label>
- <div class="col-xs-4">
- <input type="date" class="form-control" id="user_birthday" name="birthday" th:value="${user.birthday}"/>
- </div>
- </div>
- <div class="form-group">
- <div class="col-sm-offset-2 col-sm-10">
- <input class="btn btn-primary" type="submit" value="提交"/>
- <input class="btn" type="button" value="返回" onclick="history.back()"/>
- </div>
- </div>
- </form>
這里定義了一個 Form 表單用于新增或者更新用戶。
列表頁面
代碼如下:
- <table class="table table-hover table-condensed">
- <legend>
- <strong>用戶列表</strong>
- </legend>
- <thead>
- <tr>
- <th>用戶編號</th>
- <th>名稱</th>
- <th>年齡</th>
- <th>出生時間</th>
- <th>管理</th>
- </tr>
- </thead>
- <tbody>
- <tr th:each="user : ${userList}">
- <th scope="row" th:text="${user.id}"></th>
- <td><a th:href="@{/users/update/{userId}(userId=${user.id})}" th:text="${user.name}"></a></td>
- <td th:text="${user.age}"></td>
- <td th:text="${user.birthday}"></td>
- <td><a class="btn btn-danger" th:href="@{/users/delete/{userId}(userId=${user.id})}">刪除</a></td>
- </tr>
- </tbody>
- </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)】