Spring Boot Web開發與thymeleaf模板引擎

来源:https://www.cnblogs.com/thelovelybugfly/archive/2019/07/03/11123629.html
-Advertisement-
Play Games

簡介: 使用Springboot應用,選中需要的模塊, Spring已經預設將場景配置好了,只需在配置文件中少量配置就可以運行起來 自己編寫業務代碼 自動配置原理 這個場景Springboot幫我們配置了什麼、能不能修改呢?能修改哪些配置? xxxxxAutoConfiguration :幫我們給容 ...


簡介:

  • 使用Springboot應用,選中需要的模塊,
  • Spring已經預設將場景配置好了,只需在配置文件中少量配置就可以運行起來
  • 自己編寫業務代碼

自動配置原理

這個場景Springboot幫我們配置了什麼、能不能修改呢?能修改哪些配置?

xxxxxAutoConfiguration :幫我們給容器自動配置組件

xxxproperties 配置類來封裝配置文件的內容

Springboot對靜態資源的映射規則

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
  //可以設置和靜態資源有關的參數,緩存時間等
//webMVC的自動配置
WebMvcAuotConfiguration:
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            if (!this.resourceProperties.isAddMappings()) {
                logger.debug("Default resource handling disabled");
                return;
            }
            Integer cachePeriod = this.resourceProperties.getCachePeriod();
            if (!registry.hasMappingForPattern("/webjars/**")) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/").setCachePeriod(cachePeriod));
            }
            String staticPathPattern = this.mvcProperties.getStaticPathPattern();
              //靜態資源文件夾映射
            if (!registry.hasMappingForPattern(staticPathPattern)) {
      customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern).addResourceLocations(this.resourceProperties.getStaticLocations()).setCachePeriod(cachePeriod));
            }
        }

        //配置歡迎頁映射
        @Bean
        public WelcomePageHandlerMapping welcomePageHandlerMapping(ResourceProperties resourceProperties) {
            return new WelcomePageHandlerMapping(resourceProperties.getWelcomePage(),
                    this.mvcProperties.getStaticPathPattern());
        }

       //配置喜歡的圖標 即我們網頁標簽最左邊的圖標
        @Configuration
        @ConditionalOnProperty(value = "spring.mvc.favicon.enabled", matchIfMissing = true)
        public static class FaviconConfiguration {
            private final ResourceProperties resourceProperties;
            public FaviconConfiguration(ResourceProperties resourceProperties) {this.resourceProperties = resourceProperties;
            }

            @Bean
            public SimpleUrlHandlerMapping faviconHandlerMapping() {
                SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
                mapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
                  //所有  **/favicon.ico 
               mapping.setUrlMap(Collections.singletonMap("**/favicon.ico",faviconRequestHandler()));
                return mapping;
            }

            @Bean
            public ResourceHttpRequestHandler faviconRequestHandler() {
                ResourceHttpRequestHandler requestHandler = new ResourceHttpRequestHandler();
                requestHandler.setLocations(this.resourceProperties.getFaviconLocations());
                return requestHandler;
            }
        }

 靜態資源的映射

  • 所有的 /webjars/**  都去 classpath:/META-INF/resources/webjars/ 找資源; webjars:以jar包的方式引入靜態資源; http://www.webjars.org/

 

pom.xml 依賴:

<!--引入jquery-webjar-->在訪問的時候只需要寫webjars下麵資源的名稱即可
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.3.1</version>
        </dependency>

訪問地址:localhost:8080/webjars/jquery/3.3.1/jquery.js

  • "/**" 訪問當前項目的任何資源,都去(靜態資源的文件夾)找映射
    "classpath:/META-INF/resources/", 
    "classpath:/resources/",
    "classpath:/static/", 
    "classpath:/public/" 
    "/":當前項目的根路徑

     localhost:8080/abc === 預設去靜態資源文件夾裡面找abc

  • 歡迎頁; 靜態資源文件夾下的所有index.html頁面;被"/**"映射;
    • localhost:8080/ 找index頁面 
  • 所有的 **/favicon.ico 都是在靜態資源文件下找;

 模板引擎

常用的模板引擎有:JSP,Velocity、Freemarker、Thymeleaf

Springboot 推薦使用thymeleaf ,語法更簡單,功能更強大。

引入thymeleaf 

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>          
       </dependency>
SpringBoot預設的thymeleaf 版本為 2.1.6 ,該版本太低,所以我們需要手動切換thymeleaf版本
<properties>
        <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
        <!-- 佈局功能的支持程式  thymeleaf3主程式  layout2以上版本 -->
        <!-- thymeleaf2   layout1-->
        <thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
  </properties>
SpringBoot 的其他預設版本的依賴也是這樣切換,如果需要修改的話,一樣的切換思路。

配置上面這兩個的時候,啟動Springboot 會報錯誤

An attempt was made to call the method org.thymeleaf.spring5.SpringTemplateEngine.setRenderHiddenMarkersBeforeCheckboxes(Z)V but it does not exist. Its class, org.thymeleaf.spring5.SpringTemplateEngine, is available from the following locations:

    jar:file:/E:/springboot/repository/org/thymeleaf/thymeleaf-spring5/3.0.9.RELEASE/thymeleaf-spring5-3.0.9.RELEASE.jar!/org/thymeleaf/spring5/SpringTemplateEngine.class

It was loaded from the following location:

    file:/E:/springboot/repository/org/thymeleaf/thymeleaf-spring5/3.0.9.RELEASE/thymeleaf-spring5-3.0.9.RELEASE.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.thymeleaf.spring5.SpringTemplateEngine

修改為以下即可:

thymeleaf的使用

配置:

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {
    private static final Charset DEFAULT_ENCODING = Charset.forName("UTF-8");
    private static final MimeType DEFAULT_CONTENT_TYPE = MimeType.valueOf("text/html");
  //只要我們把HTML頁面放在classpath:/templates/,thymeleaf就能自動渲染;
  public static final String DEFAULT_PREFIX = "classpath:/templates/";
public static final String DEFAULT_SUFFIX = ".html";

使用:

 1,在html 頁面上導入thymeleaf的命名空間 , 不導入也可以,只是在寫代碼的時候,沒有相應的代碼提示。

<html lang="en" xmlns:th="http://www.thymeleaf.org">

thymeleaf的語法

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>成功!</h1>
    <!--th:text 將div裡面的文本內容設置為 -->
    <div th:text="${hello}">這是顯示歡迎信息</div>
</body>
</html>

語法規則:

1)、th:text;改變當前元素裡面的文本內容;

    th:任意html屬性;來替換原生屬性的值 

2)、表達式

Simple expressions:(表達式語法)
    Variable Expressions: ${...}:獲取變數值;OGNL;
            1)、獲取對象的屬性、調用方法
            2)、使用內置的基本對象:
                #ctx : the context object.
                #vars: the context variables.
                #locale : the context locale.
                #request : (only in Web Contexts) the HttpServletRequest object.
                #response : (only in Web Contexts) the HttpServletResponse object.
                #session : (only in Web Contexts) the HttpSession object.
                #servletContext : (only in Web Contexts) the ServletContext object.               
                ${session.foo}
            3)、內置的一些工具對象:
#execInfo : information about the template being processed.
#messages : methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
#uris : methods for escaping parts of URLs/URIs
#conversions : methods for executing the configured conversion service (if any).
#dates : methods for java.util.Date objects: formatting, component extraction, etc.
#calendars : analogous to #dates , but for java.util.Calendar objects.
#numbers : methods for formatting numeric objects.
#strings : methods for String objects: contains, startsWith, prepending/appending, etc.
#objects : methods for objects in general.
#bools : methods for boolean evaluation.
#arrays : methods for arrays.
#lists : methods for lists.
#sets : methods for sets.
#maps : methods for maps.
#aggregates : methods for creating aggregates on arrays or collections.
#ids : methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

    Selection Variable Expressions: *{...}:選擇表達式:和${}在功能上是一樣;
        補充:配合 th:object="${session.user}:
   <div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
    <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
    <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
    </div>
    
    Message Expressions: #{...}:獲取國際化內容
    Link URL Expressions: @{...}:定義URL;
            @{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表達式
            <div th:insert="~{commons :: main}">...</div>
            
Literals(字面量)
      Text literals: 'one text' , 'Another one!' ,…
      Number literals: 0 , 34 , 3.0 , 12.3 ,…
      Boolean literals: true , false
      Null literal: null
      Literal tokens: one , sometext , main ,…
Text operations:(文本操作)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
Arithmetic operations:(數學運算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布爾運算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比較運算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:條件運算(三元運算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _ 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 上一篇說了使用位運算來進行子集輸出,這裡使用回溯的方法來進行排序。 回溯的思想,我的理解就是: 把解的所有情況轉換為樹或者圖,然後用深度優先的原則來對所有的情況進行遍歷解析。 當然,因為問題中會包涵這各種各樣的限制條件,我們可以用這些限制條件去減少遍歷的分支。 其實,比較著名的就是0 1背包問題,這 ...
  • [toc] 自定義 Admin 樣式與功能 1 頁面修改中文 1.1 語言設置為中文 settings.py 修改結果 1.2 應用管理設置為中文 應用/apps.py 修改結果 1.3 資料庫表設置為中文 應用/models.py 預設資料庫表在後臺中顯示都為複數形式,而中文沒有複數形式,因此將兩 ...
  • [TOC] 原文鏈接: "表格樹控制項QtTreePropertyBrowser編譯成動態庫(設計師插件)" 一、回顧 上一篇文章 "超級實用的表格樹控制項 QtTreePropertyBrowser" 講了怎麼去編譯QtTreePropertyBrowser庫,並且可以簡單使用。由於我下載的庫是基於Q ...
  • 1.jieba分詞的安裝 直接在cmd視窗當中pip install即可 2.jieba分詞的介紹 jieba分詞是目前比較好的中文分片語件之一,jieba分詞支持三種模式的分詞(精確模式、全模式、搜索引擎模式),並且支持自定義詞典(這一點在特定的領域很重要,有時候需要根據領域的需要來添加特定的詞典 ...
  • 裝飾器函數 開發封閉原則(先從別人偷來一波好文章,簡單易懂)   什麼是開放封閉原則?有的同學問開放,封閉這是兩個反義詞這還能組成一個原則麽?這不前後矛盾麽?其實不矛盾。開放封閉原則是分情況討論的。   我們的軟體一旦上線之後(比如你的軟體主要是多個函數組成的 ...
  • 1題目:在一個二維數組中(每個一維數組的長度相同),每一行都按照從左到右遞增的順序排序,每一列都按照從上到下遞增的順序排序。請完成一個函數,輸入這樣的一個二維數組和一個整數,判斷數組中是否含有該整數。 2思路:首先選取數組中右上角的數字。如果該數字等於要查找的數字,查找過程結束;如果該數字大於要查找 ...
  • 一、基礎案例 1、基礎案例概覽 歷時一個半月,SpringBoot2.0基礎案例的文章基本更新完畢了,基礎案例包含了SpringBoot的基礎教程,高級應用,日誌配置,資料庫使用,事務管理等。關於SpringBoot2.0的基礎案例就更新到這裡了,後續會更新SpringBoot2.0和各種中間件的整 ...
  • 單列集合框架體系 List 集合體系 主要實現類 依次為 ArrayList,LinkedList,Vector 。 List介面主要特征: 有序,可重覆,有索引,底層容量是動態擴容的。(代碼以JDK 1.8為例) ArrayList:是List介面的主要實現類,底層用數組實現: ,transien ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...