5颗祝、SpringBoot之WEB開(kāi)發(fā)和thymeleaf模板引擎

1浊闪、簡(jiǎn)介

使用SpringBoot恼布;

1)、創(chuàng)建SpringBoot應(yīng)用搁宾,選中我們需要的模塊折汞;

2)、SpringBoot已經(jīng)默認(rèn)將這些場(chǎng)景配置好了盖腿,只需要在配置文件中指定少量配置就可以運(yùn)行起來(lái)

3)爽待、自己編寫業(yè)務(wù)代碼;

自動(dòng)配置原理翩腐?

這個(gè)場(chǎng)景SpringBoot幫我們配置了什么鸟款?能不能修改?能修改哪些配置茂卦?能不能擴(kuò)展何什?xxx

xxxxAutoConfiguration:幫我們給容器中自動(dòng)配置組件;
xxxxProperties:配置類來(lái)封裝配置文件的內(nèi)容等龙;

2处渣、SpringBoot對(duì)靜態(tài)資源的映射規(guī)則;

@ConfigurationProperties(prefix = "spring.resources", ignoreUnknownFields = false)
public class ResourceProperties implements ResourceLoaderAware {
  //可以設(shè)置和靜態(tài)資源有關(guān)的參數(shù)蛛砰,緩存時(shí)間等
    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();
            //靜態(tài)資源文件夾映射
            if (!registry.hasMappingForPattern(staticPathPattern)) {
                customizeResourceHandlerRegistration(
                        registry.addResourceHandler(staticPathPattern)
                                .addResourceLocations(
                                        this.resourceProperties.getStaticLocations())
                        .setCachePeriod(cachePeriod));
            }
        }

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

       //配置喜歡的圖標(biāo)
        @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;
            }

        }

==1)霍比、所有 /webjars/** ,都去 classpath:/META-INF/resources/webjars/ 找資源暴备;==

? webjars:以jar包的方式引入靜態(tài)資源;

http://www.webjars.org/

image.png

pom文件里面引入:

 <dependency>
     <groupId>org.webjars</groupId>
     <artifactId>jquery</artifactId>
     <version>3.2.1</version>
</dependency>

==2)们豌、"/**" 訪問(wèn)當(dāng)前項(xiàng)目的任何資源涯捻,都去(靜態(tài)資源的文件夾)找映射==

"classpath:/META-INF/resources/", 
"classpath:/resources/",
"classpath:/static/", 
"classpath:/public/" 
"/":當(dāng)前項(xiàng)目的根路徑

localhost:8080/abc === 去靜態(tài)資源文件夾里面找abc

==3)、歡迎頁(yè)望迎; 靜態(tài)資源文件夾下的所有index.html頁(yè)面障癌;被"/**"映射;==

? localhost:8080/ 找index頁(yè)面

==4)辩尊、所有的 **/favicon.ico 都是在靜態(tài)資源文件下找涛浙;==

3、模板引擎

JSP摄欲、Velocity轿亮、Freemarker、Thymeleaf


image.png

SpringBoot推薦的Thymeleaf胸墙;

語(yǔ)法更簡(jiǎn)單我注,功能更強(qiáng)大;

1迟隅、引入thymeleaf但骨;

  <!--引入thymeleaf模板引擎-->
 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2励七、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");

    public static final String DEFAULT_PREFIX = "classpath:/templates/";

    public static final String DEFAULT_SUFFIX = ".html";
    //

只要我們把HTML頁(yè)面放在classpath:/templates/,thymeleaf就能自動(dòng)渲染奔缠;
例如我寫一個(gè)測(cè)試類:

 /**
     * 該處返回 "success"返回的是 resources/templates目錄下面的頁(yè)面
     * 該出要返回的是頁(yè)面掠抬,所以不能配置@ResponseBody注解,如果配置了該注解會(huì)以字符串直接輸出"success"
     * @return success.html
     */
    @RequestMapping("/success")
    public String success(){
        return "success";
    }

然后 resources/templates目錄下新建success.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>跳轉(zhuǎn)成功頁(yè)面</h1>
</body>
</html>
image.png

使用:

1校哎、導(dǎo)入thymeleaf的名稱空間

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

2两波、使用thymeleaf語(yǔ)法;
后端代碼改寫成:


<!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里面的文本內(nèi)容設(shè)置為 -->
    <div th:text="${hello}">這是顯示歡迎信息</div>
</body>
</html>
image.png

3雨女、語(yǔ)法規(guī)則

1)、th:text阳准;改變當(dāng)前元素里面的文本內(nèi)容氛堕;

? th:任意html屬性;來(lái)替換原生屬性的值

image.png

2)野蝇、表達(dá)式讼稚?

Simple expressions:(表達(dá)式語(yǔ)法)
    Variable Expressions: ${...}:獲取變量值;OGNL绕沈;
            1)锐想、獲取對(duì)象的屬性、調(diào)用方法
            2)乍狐、使用內(nèi)置的基本對(duì)象:
                #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)赠摇、內(nèi)置的一些工具對(duì)象:
#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: *{...}:選擇表達(dá)式:和${}在功能上是一樣;
        補(bǔ)充:配合 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: #{...}:獲取國(guó)際化內(nèi)容
    Link URL Expressions: @{...}:定義URL浅蚪;
            @{/order/process(execId=${execId},execType='FAST')}
    Fragment Expressions: ~{...}:片段引用表達(dá)式
            <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:(數(shù)學(xué)運(yùn)算)
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
Boolean operations:(布爾運(yùn)算)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
Comparisons and equality:(比較運(yùn)算)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
Conditional operators:條件運(yùn)算(三元運(yùn)算符)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
Special tokens:
    No-Operation: _ 

數(shù)據(jù)渲染到頁(yè)面相關(guān)用法:

html頁(yè)面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>跳轉(zhuǎn)成功頁(yè)面</h1>

<div th:text="${hello}"></div>

<hr/>
<div th:text="${hello}"></div>
<div th:utext="${hello}"></div>

<hr/>
<h4 th:text="${user}" th:each="user:${users}"></h4>
<hr/>

<h4>
    <span th:each="user:${users}" > [[${user}]] </span>
</h4>
</body>
</html>

后端代碼:

@RequestMapping("/success")
    public String success(Map<String,Object> map){
        map.put("hello","你好");
        map.put("users", Arrays.asList("張三","李四","王五"));
        return "success";
    }

效果圖:


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末藕帜,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子惜傲,更是在濱河造成了極大的恐慌洽故,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,968評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件盗誊,死亡現(xiàn)場(chǎng)離奇詭異时甚,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)哈踱,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門荒适,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人开镣,你說(shuō)我怎么就攤上這事吻贿。” “怎么了哑子?”我有些...
    開(kāi)封第一講書人閱讀 153,220評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵舅列,是天一觀的道長(zhǎng)肌割。 經(jīng)常有香客問(wèn)我,道長(zhǎng)帐要,這世上最難降的妖魔是什么把敞? 我笑而不...
    開(kāi)封第一講書人閱讀 55,416評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮榨惠,結(jié)果婚禮上奋早,老公的妹妹穿的比我還像新娘。我一直安慰自己赠橙,他們只是感情好耽装,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,425評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著期揪,像睡著了一般掉奄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上凤薛,一...
    開(kāi)封第一講書人閱讀 49,144評(píng)論 1 285
  • 那天姓建,我揣著相機(jī)與錄音,去河邊找鬼缤苫。 笑死速兔,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的活玲。 我是一名探鬼主播涣狗,決...
    沈念sama閱讀 38,432評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼舒憾!你這毒婦竟也來(lái)了镀钓?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書人閱讀 37,088評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤珍剑,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后死陆,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體招拙,經(jīng)...
    沈念sama閱讀 43,586評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,028評(píng)論 2 325
  • 正文 我和宋清朗相戀三年措译,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了别凤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,137評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡领虹,死狀恐怖规哪,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情塌衰,我是刑警寧澤诉稍,帶...
    沈念sama閱讀 33,783評(píng)論 4 324
  • 正文 年R本政府宣布蝠嘉,位于F島的核電站,受9級(jí)特大地震影響杯巨,放射性物質(zhì)發(fā)生泄漏蚤告。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,343評(píng)論 3 307
  • 文/蒙蒙 一服爷、第九天 我趴在偏房一處隱蔽的房頂上張望杜恰。 院中可真熱鬧,春花似錦仍源、人聲如沸心褐。這莊子的主人今日做“春日...
    開(kāi)封第一講書人閱讀 30,333評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)逗爹。三九已至,卻和暖如春戳表,著一層夾襖步出監(jiān)牢的瞬間桶至,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書人閱讀 31,559評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工匾旭, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留镣屹,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,595評(píng)論 2 355
  • 正文 我出身青樓价涝,卻偏偏與公主長(zhǎng)得像女蜈,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子色瘩,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,901評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容