免费视频淫片aa毛片_日韩高清在线亚洲专区vr_日韩大片免费观看视频播放_亚洲欧美国产精品完整版

打開APP
userphoto
未登錄

開通VIP,暢享免費電子書等14項超值服

開通VIP
Spring Boot 整合 Thymeleaf 完整 Web 案例

摘要: 原創(chuàng)出處:www.bysocket.com 泥瓦匠BYSocket 希望轉載,保留摘要,謝謝!

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

  • 數據 數據是信息的表現(xiàn)形式和載體,可以是符號、文字、數字、語音、圖像、視頻等。數據和信息是不可分離的,數據是信息的表達,信息是數據的內涵。數據本身沒有意義,數據只有對實體行為產生影響時才成為信息。

  • 模板 模板,是一個藍圖,即一個與類型無關的類。編譯器在使用模板時,會根據模板實參對模板進行實例化,得到一個與類型相關的類。

  • 模板引擎 模板引擎(這里特指用于Web開發(fā)的模板引擎)是為了使用戶界面與業(yè)務數據(內容)分離而產生的,它可以生成特定格式的文檔,用于網站的模板引擎就會生成一個標準的HTML文檔。

  • 結果文檔 一種特定格式的文檔,比如用于網站的模板引擎就會生成一個標準的HTML文檔。

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

  • 頁面渲染

  • 文檔生成

  • 代碼生成

  • 所有 “數據+模板=文本” 的應用場景

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

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

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

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. 工程結構

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

  1. ├── pom.xml

  2. └── src

  3.    ├── main

  4.       ├── java

  5.         └── spring

  6.             └── boot

  7.                 └── core

  8.                     ├── QuickStartApplication.java

  9.                     ├── domain

  10.                       ├── User.java

  11.                       └── UserRepository.java

  12.                     ├── service

  13.                       ├── UserService.java

  14.                       └── impl

  15.                           └── UserServiceImpl.java

  16.                     └── web

  17.                         └── UserController.java

  18.       └── resources

  19.           ├── application.properties

  20.           ├── static

  21.             ├── css

  22.               └── default.css

  23.             └── images

  24.                 └── favicon.ico

  25.           └── templates

  26.               ├── userForm.html

  27.               └── userList.html

  28.    └── test

  29.        └── java

  30.            └── spring

  31.                └── boot

  32.                    └── core

  33.                        ├── QuickStartApplicationTests.java

  34.                        └── domain

  35.                            └── UserRepositoryTests.java

對應目錄:

  • org.spring.springboot.controller - Controller 層

  • org.spring.springboot.dao - 數據操作層 DAO

  • org.spring.springboot.domain - 實體類

  • org.spring.springboot.service - 業(yè)務邏輯層

  • Application - 應用啟動類

  • application.properties - 應用配置文件

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

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

  • templates 目錄是存放視圖

3. 編譯運行工程

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

  1. cd chapter-2-spring-boot-quick-start

  2. mvn clean install

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

用戶編輯頁面: 

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

工程代碼:

1. pom.xml Thymeleaf 依賴

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

  1.    org.springframework.boot

  2.    spring-boot-starter-thymeleaf

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. <> 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.    4.0.0

  5.    spring.boot.core

  6.    chapter-2-spring-boot-quick-start

  7.    0.0.1-SNAPSHOT

  8.    jar

  9.    chapter-2-spring-boot-quick-start

  10.    第二章快速入門案例

  11.    

  12.        org.springframework.boot

  13.        spring-boot-starter-parent

  14.        1.5.7.RELEASE

  15.    

  16.    

  17.        UTF-8

  18.        UTF-8

  19.        1.8

  20.    

  21.    

  22.        

  23.        

  24.            org.springframework.boot

  25.            spring-boot-starter-web

  26.        

  27.        

  28.        

  29.            org.springframework.boot

  30.            spring-boot-starter-test

  31.            test

  32.        

  33.        

  34.        

  35.            org.springframework.boot

  36.            spring-boot-starter-data-jpa

  37.        

  38.        

  39.        

  40.            com.h2database

  41.            h2

  42.            runtime

  43.        

  44.        

  45.        

  46.            org.springframework.boot

  47.            spring-boot-starter-thymeleaf

  48.        

  49.    

  50.    

  51.        

  52.            

  53.            

  54.                org.springframework.boot

  55.                spring-boot-maven-plugin

  56.            

  57.        

  58.    

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.    @Autowired

  5.    UserService userService;          // 用戶服務層

  6.    /**

  7.     *  獲取用戶列表

  8.     *    處理 '/users' 的 GET 請求,用來獲取用戶列表

  9.     *    通過 @RequestParam 傳遞參數,進一步實現(xiàn)條件查詢或者分頁查詢

  10.     */

  11.    @RequestMapping(method = RequestMethod.GET)

  12.    public String getUserList(ModelMap map) {

  13.        map.addAttribute('userList', userService.findAll());

  14.        return 'userList';

  15.    }

  16.    /**

  17.     * 顯示創(chuàng)建用戶表單

  18.     *

  19.     */

  20.    @RequestMapping(value = '/create', method = RequestMethod.GET)

  21.    public String createUserForm(ModelMap map) {

  22.        map.addAttribute('user', new User());

  23.        map.addAttribute('action', 'create');

  24.        return 'userForm';

  25.    }

  26.    /**

  27.     *  創(chuàng)建用戶

  28.     *    處理 '/users' 的 POST 請求,用來獲取用戶列表

  29.     *    通過 @ModelAttribute 綁定參數,也通過 @RequestParam 從頁面中傳遞參數

  30.     */

  31.    @RequestMapping(value = '/create', method = RequestMethod.POST)

  32.    public String postUser(@ModelAttribute User user) {

  33.        userService.insertByUser(user);

  34.        return 'redirect:/users/';

  35.    }

  36.    /**

  37.     * 顯示需要更新用戶表單

  38.     *    處理 '/users/{id}' 的 GET 請求,通過 URL 中的 id 值獲取 User 信息

  39.     *    URL 中的 id ,通過 @PathVariable 綁定參數

  40.     */

  41.    @RequestMapping(value = '/update/{id}', method = RequestMethod.GET)

  42.    public String getUser(@PathVariable Long id, ModelMap map) {

  43.        map.addAttribute('user', userService.findById(id));

  44.        map.addAttribute('action', 'update');

  45.        return 'userForm';

  46.    }

  47.    /**

  48.     * 處理 '/users/{id}' 的 PUT 請求,用來更新 User 信息

  49.     *

  50.     */

  51.    @RequestMapping(value = '/update', method = RequestMethod.POST)

  52.    public String putUser(@ModelAttribute User user) {

  53.        userService.update(user);

  54.        return 'redirect:/users/';

  55.    }

  56.    /**

  57.     * 處理 '/users/{id}' 的 GET 請求,用來刪除 User 信息

  58.     */

  59.    @RequestMapping(value = '/delete/{id}', method = RequestMethod.GET)

  60.    public String deleteUser(@PathVariable Long id) {

  61.        userService.delete(id);

  62.        return 'redirect:/users/';

  63.    }

  64. }

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

Form 表單頁面

核心代碼:

  1. <> th:action='@{/users/{action}(action=${action})}' method='post' class='form-horizontal'>

  2.                <> type='hidden' name='id' th:value='${user.id}'/>

  3.                <> class='form-group'>

  4.                    <> for='user_name' class='col-sm-2 control-label'>名稱

  5.                    <> class='col-xs-4'>

  6.                        <> type='text' class='form-control' id='user_name' name='name' th:value='${user.name}' />

  7.                    

  •                

  •                <> class='form-group'>

  •                    <> for='user_age' class='col-sm-2 control-label'>年齡:

  •                    <> class='col-xs-4'>

  •                        <> type='text' class='form-control' id='user_age' name='age' th:value='${user.age}'/>

  •                    

  •                

  •                <> class='form-group'>

  •                    <> for='user_birthday' class='col-sm-2 control-label'>出生日期:

  •                    <> class='col-xs-4'>

  •                        <> type='date' class='form-control' id='user_birthday' name='birthday' th:value='${user.birthday}'/>

  •                    

  •                

  •                <> class='form-group'>

  •                    <> class='col-sm-offset-2 col-sm-10'>

  •                        <> class='btn btn-primary' type='submit' value='提交'/>  

  •                        <> class='btn' type='button' value='返回' onclick='history.back()'/>

  •                    

  •                

  •            

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

    列表頁面

    代碼如下:

    1. <> class='table table-hover table-condensed'>

    2.                

    3.                    用戶列表

    4.                

    5.                

    6.                    

    7.                        用戶編號

    8.                        名稱

    9.                        年齡

    10.                        出生時間

    11.                        管理

    12.                    

    13.                

    14.                

    15.                    <> th:each='user : ${userList}'>

    16.                        <> scope='row' th:text='${user.id}'>

    17.                        <> th:href='@{/users/update/{userId}(userId=${user.id})}' th:text='${user.name}'>

    18.                        <> th:text='${user.age}'>

    19.                        <> th:text='${user.birthday}'>

    20.                        <> class='btn btn-danger' th:href='@{/users/delete/{userId}(userId=${user.id})}'>刪除

    21.                    

    22.                

    23.            

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

    Tymeleaf 的語法糖

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

    三、本文小結

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

    如以上文章或鏈接對你有幫助的話,別忘了在文章結尾處評論哈~ 你也可以點擊頁面右邊“分享”懸浮按鈕哦,讓更多的人閱讀這篇文章。


    還有,掃掃一起交流學習:


    本站僅提供存儲服務,所有內容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權內容,請點擊舉報。
    打開APP,閱讀全文并永久保存 查看更多類似文章
    猜你喜歡
    類似文章
    Thymeleaf系列一 Spring boot 集成Thymeleaf
    Spring Boot中使用Redis數據庫
    SpringBoot2.0 監(jiān)聽器ApplicationListener的使用
    Spring4新特性:
    Spring Boot使用Spring Security實現(xiàn)權限控制
    利用 Spring Boot 設計風格良好的Restful API及錯誤響應
    更多類似文章 >>
    生活服務
    分享 收藏 導長圖 關注 下載文章
    綁定賬號成功
    后續(xù)可登錄賬號暢享VIP特權!
    如果VIP功能使用有故障,
    可點擊這里聯(lián)系客服!

    聯(lián)系客服