欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring Boot Web开发与thymeleaf模板引擎

程序员文章站 2022-05-03 22:16:38
简介: 使用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包的方式引入静态资源; /

 Spring Boot Web开发与thymeleaf模板引擎

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

Spring Boot Web开发与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 的其他默认版本的依赖也是这样切换,如果需要修改的话,一样的切换思路。

Spring Boot Web开发与thymeleaf模板引擎

配置上面这两个的时候,启动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

修改为以下即可:
Spring Boot Web开发与thymeleaf模板引擎

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属性;来替换原生属性的值 

Spring Boot Web开发与thymeleaf模板引擎

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: _