首页 > 编程语言 > 详细

SpringBoot-10-Thymeleaf

时间:2020-09-19 13:21:09      阅读:66      评论:0      收藏:0      [点我收藏+]

1、SpringBoot支持的视图技术,模板引擎

  • FreeMarker

    一个基于模板生成输出文本(HTML页面、电子邮件、配置文件等)的模板引擎

    不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入所开发产品的组件

  • Groovy

    一种基于JVM的敏捷开发语言

  • Thymeleaf

    一种用于Web和独立环境的现代服务器端的Java模板引擎

    能够处理HTML、XML、Javascript、CSS、纯文本

  • Mustache

    轻逻辑的模板引擎

    一个JS模板,用于对JS进行分离展示

 

2、为什么要使用模板引擎?

  • 前端交给我们的页面是HTML页面,使用springBoot开发前,我们需把HTML页面转成Jsp页面

  • 但是SpringBoot不支持Jsp

    • SpringBoot是以jar的方式,不是war

    • SpringBoot用的是默认的tomcat

  • 不支持jsp,如果使用纯静态页面的方式,会给开发带来很大的麻烦

 

3、模板引擎思想

技术分享图片

 

4、Thymeleaf介绍

  • Thymeleaf概念

    • 一种现代的基于服务器端的Java模板引擎技术

    • 一个优秀的面向Java的XML、XHTML、HTML5页面模板

    • 具有丰富的标签语言、函数和表达式

 

  • 常用标签

    • 页面包含

      • th:insert:页面片段包含(类似JSP中的include标签)

      • th:replace:页面片段包含(类似JSP中的include标签)

    • 元素遍历

      • th:each:元素遍历(类似于JSP中的c:forEach标签)

      • 测试

        • 后端

          @Controller
          public class TestController {
          ?
             @GetMapping("/test")
             public String Test(Model model){
                 model.addAttribute("users", Arrays.asList("andy","lucy","lisa"));
                 return "test";
            }
          }
        • 前端页面

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

          <div th:each="user:${users}">[[${user}]]</div>
        • 浏览器显示

          技术分享图片

    • 条件判断

      • th:if:条件判断,条件成立时显示th标签的内容

      • th:unless:条件判断,条件不成立时显示th标签的内容

      • th:switch:条件判断,进行选择性匹配

      • th:case:th:switch分支的条件判断

    • 替换对象

      • th:object

    • 定义局部变量

      • th:with

    • 属性修改

      • th:attr:通用属性修改

      • th:attrprepend:通用属性修改,将计算结果追加前缀到现有属性值

      • th:attrapend:通用属性修改,将计算结果追加后缀到现有属性值

      • th:value:属性值修改,指定标签属性值

    • 链接

      • th:href:用于设定链接地址

      • th:src:用于设定链接地址

    • 文本内容

      • th:text:用于指定标签显示的文本内容

      • th:utext:用于指定标签显示的文本内容,对特殊标签不转义

      • 测试

        • 后端

          @Controller
          public class TestController {
          ?
             @GetMapping("/test")
             public String Test(Model model){
                 model.addAttribute("hello1","<h1>hello,springBoot</h1>");
                 model.addAttribute("hello2","<h1>hello,springBoot</h1>");
                 return "test";
            }
          }
        • 前端页面

          <div th:text="${hello1}"></div>
          <div th:utext="${hello2}"></div>
        • 浏览器显示

          技术分享图片

    • 声明片段

      • th:fragment

    • 移除片段

      • th:remove

 

  • 标准表达式

    • 变量表达式:${...}

      • 变量表达式主要用于获取上下文中的变量值

        <!--
        模板引擎页面数据动态替换:
        若当前程序没有启动或者当前上下文中不存在变量hello,该片段会显示标签默认值”Spring Boot“
        若当前上下文中存在变量hello并且程序已经启动,变量hello的值将替换标签默认值
        -->
        <div th:text="${hello1}">Spring Boot</div>
      • Thymeleaf为变量所在域提供了一些内置对象

        • #ctx:上下文对象

        • #vars:上下文变量

        • #locale:上下文区域设置

        • #request:(仅限Web Context)HttpServletRequest对象

        • #reponse:(仅限Web Context)HttpServletReponse对象

        • #session:(仅限Web Context)HttpSession对象

        • #servletContext:(仅限Web Context)ServletContext对象

      • 内置的一些工具对象

        • #execInfo:

        • #uris:转义部分url/uri的方法

        • #conversions:执行配置的转换服务(如果有的话)的方法。

        • #dates:方法java.util.Date日期对象:格式化、组件提取等。

        • #calendars:类似于日期,但是java.util.Calendar日历物体。

        • #numbers:格式化数字对象的方法。

        • #strings:字符串对象的方法:contains、startsWith、prepending/appending等。

        • #objects:通常用于对象的方法。

        • #bools:布尔求值的方法。

        • #arrays: 数组的方法。

        • #lists:列表的方法。

        • #sets:集合的方法。

        • #maps:map的方法。

        • #aggregates:在数组或集合上创建聚合的方法。

        • #aggregates:在数组或集合上创建聚合的方法。

           

    • 选择变量表达式:*{...}

      • 一般用于从被选定对象中获取属性值

      • 如果没有选定对象,和变量表达式一样

    • 消息表达式:#{...}

      • 主要用于Thymeleaf模板页面国际化内容的动态替换和展示

    • 链接URL表达式:@{...}

      • 一般用于页面跳转或者资源的引入

      • 在有参表达式中,需要按照@{路径(参数名称=参数值,参数名称=参数值...)}的形式编写,该参数的值可以通过变量表达式来传递动态参数值

    • 片段表达式:~{...}

      • 将标记片段移动到模板中

      • 最常见的用法是使用th:insert或th:replace属性插入片段

 

  • 字面量

    • 文本:单引号 ,如:‘one text’

    • 数字:直接写出,如:0.36

    • 布尔:true、false

    • 空值:null

    • 文字标记:one、sometext、main......

 

  • 文本操作

    • 字符串连接:+

    • 文字替换:|The name is ${name}|

 

  • 算术运算

    • 二元运算:+、-、*、/、%

    • 一元运算符:-

 

  • 布尔操作

    • 二元运算:and、or

    • 一元运算符:!,not

 

  • 比较运算

    • 不等运算:>(gt)、<(lt)、 >=(ge)、<=(le)

    • 相等运算:==(eq)、!=(ne)

 

  • 三元条件运算

    • if-then:(if) ? (then)

    • if-then-else:(if) ? (then) : (else)

    • Default:(value) ?: (defaultvalue)

 

  • 分隔表达式

    • _

 

5、Thymeleaf使用

  • Thymeleaf引入

    • Thymeleaf官网

    • Thymeleaf在Github的主页

    • Spring官方文档

      <dependency>
         <groupId>org.thymeleaf</groupId>
         <artifactId>thymeleaf-spring5</artifactId>
      </dependency>
      ?
      <dependency>
         <groupId>org.thymeleaf.extras</groupId>
         <artifactId>thymeleaf-extras-java8time</artifactId>
      </dependency>
      • Thymeleaf导入依赖后引入的jar包

        技术分享图片

 

  • 使用Thymeleaf的文件存放位置

    • 把html页面放在resources下的thymeleafs包下

    • 原因:由ThymeleafProperties.class里得出

      public class ThymeleafProperties {
         //前缀
         public static final String DEFAULT_PREFIX = "classpath:/templates/";
         //后缀
         public static final String DEFAULT_SUFFIX = ".html";

 

6、使用thymeleaf实现登录表单

  • 1、创建SpringBoot项目,引入Thymeleaf依赖

  • 2、编写配置文件

    #thymaleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默认false
    spring:
    thymeleaf:
      cache: false
  • 3、创建Web控制类

    @Controller
    public class LoginController {
    ?
       @RequestMapping("/toLogin")
       public String toLogin(Model model){
           model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
           return "login";
      }
    }
  • 4、编写前端页面

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
       <meta charset="UTF-8">
       <title>用户登录页面</title>
       
       <!--引入外部资源-->
       <link th:href="@{/css/signIn.css}" rel="stylesheet">
    </head>
    <body>
    <form class="form-signIn">
       
       <!--引入图片-->
       <img class="img" th:src="@{/image/222.jpg}" th:width="72" th:height="72"/>
       <h1>请登录</h1>
       <input type="text" placeholder="用户名" required="" autofocus="">
       <input type="password" placeholder="密码" required="">
       <div>
           <label>
               <input type="checkbox" value="remember-me">记住我
           </label>
       </div>
       <button type="submit">登录</button><br>
       
       <!--数据动态替换-->
       <span th:text="${currentYear}">2020</span>-<span th:text="${currentYear}+1">2021</span>
    </form>
    </body>
    </html>
  • 效果展示

    技术分享图片

7、使用ThymeLeaf配置国际化页面

  • 1、编写多语言国际化文件

    • login.properties

      login.tip=请登录
      login.username=用户名
      login.password=密码
      login.rememberMe=记住我
      login.button=登录
    • login_zh_CN.properties

      login.tip=请登录
      login.username=用户名
      login.password=密码
      login.rememberMe=记住我
      login.button=登录
    • login.en_US.properties

      login.tip=Please sign in
      login.username=Username
      login.password=Password
      login.rememberMe=Remember me
      login.button=Login
  • 2、编写配置文件

    #thymaleaf页面缓存设置(默认为true),开发中方便调试应设置为false,上线稳定后应保持默认false
    spring:
    thymeleaf:
      cache: false
    ?
    #配置国际化文件基础名
    messages:
      basename: i18n.login
  • 3、定制区域信息解析器

    @Configuration
    public class MyLocalResolver implements LocaleResolver {
    ?
       //自定义区域解析方式,解析请求
       @Override
       public Locale resolveLocale(HttpServletRequest httpServletRequest) {
           //获取请求中的语言参数
           String language = httpServletRequest.getParameter("l");
    ?
           //如果没有就使用默认的
           Locale locale = Locale.getDefault();
    ?
           //如果请求的链接携带了国际化的参数
           if(!StringUtils.isEmpty(language)){
               //zh_CN
               String[] split = language.split("_");
               //国家,地区
               locale = new Locale(split[0], split[1]);
          }
           return locale;
      }
    ?
       @Override
       public void setLocale(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Locale locale) {
      }
       //将自定义的MyLocalResolver类重新注册一个类型LocaleResolver的Bean组件
       @Bean
       public LocaleResolver localeResolver(){
           return new MyLocalResolver();
      }
    }
  • 4、前端页面,使用国际化

    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
       <meta charset="UTF-8">
       <title>用户登录页面</title>
       <link th:href="@{/css/signIn.css}" rel="stylesheet">
    </head>
    <body>
    <form class="form-signIn">
       <img class="img" th:src="@{/image/222.jpg}" th:width="72" th:height="72"/>
    ?
       <h1 th:text="#{login.tip}">请登录</h1>
    ?
       <input type="text" th:placeholder="#{login.username}" required="" autofocus="">
    ?
       <input type="password" th:placeholder="#{login.password}" required="">
    ?
       <div>
           <label>
               <input type="checkbox" value="remember-me">[[#{login.rememberMe}]]
           </label>
       </div>
    ?
       <button type="submit">[[#{login.button}]]</button><br>
    ?
       <p>
           <span th:text="${currentYear}">2020</span>-<span th:text="${currentYear}+1">2021</span>
       </p>
    ?
       <!--使用区域信息解析器,解析请求-->
       <a th:href="@{/toLogin(l=‘zh_CN‘)}">中文</a>
       <a th:href="@{/toLogin(l=‘en_US‘)}">English</a>
    </form>
    </body>
    </html>
  • 5、效果展示

    • 点击中文

      技术分享图片

    • 点击英文

    • 技术分享图片 

SpringBoot-10-Thymeleaf

原文:https://www.cnblogs.com/LittleSkinny/p/13695423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!