视图解析---Thymeleaf模板引擎

1,745 阅读5分钟

视图解析---Thymeleaf模板引擎

1、什么是模板引擎

视图解析:SpringBoot在处理完某个请求后,想要跳转到某个页面的过程。

当我们开发传统项目的时候,需要我们自己编写前端页面进行渲染结果,这时就需要模板引擎,以前使用的方式是通过转发或者重定向到某个jsp页面,使用jsp的好处就是可以在我们查出一些数据并转发到jsp页面后,可以用轻松实现对这些数据的显示以及交互。jsp的功能很强大,其中可以编写java代码。但是Springboot方式默认打包方式为jar包,不是war包,而且使用的还是嵌入式的tomcat容器,jar包是一个压缩包,所以jsp不能在压缩包里面编译,所以SpringBoot默认不支持jsp,需要引入第三方模板引擎技术实现页面渲染【实际上jsp也是一种模板引擎】。

在开发前后端不分离的springboot项目时,不能使用jsp,如果我们直接用纯静态页面的方式,会给我们的开发带来非常大的麻烦。所以springboot就会推荐我们使用模板引擎。Thymeleaf是用来开发Web和独立环境项目的服务器端的Java模版引擎

Thymeleaf是springboot中的后端的java模板引擎,使用方法与vue有很多相似之处,可以获取域中的信息并在页面中显示,Thymeleaf自带的视图解析器为resources目录下的templates 文件夹,以html 结尾,templates目录下的html文件属于模板文件,不可以直接访问,必须通过视图解析器解析后才可以进行访问

我们将后台数据放到model对象中,然后通过Template模板引擎中的具体语法获取数据,然后进行渲染,然后以静态页面的形式将数据在前端进行显示

模板引擎具体作用:我们写了一个页面模板,但是这个模板中的一些值是动态的,我们就在这些值得位置写一些表达式来获取数据。这些值去哪获取呢?我们可以将后台的数据进行组装,即组装到一个ModelAndView这个对象中,表达式就从这个对象中获取。然后我们将这个页面模板和这些数据交给模板引擎,模板引擎将其中的表达式进行解析,将获取的数据填充到我们指定的位置,然后将这些数据最终生成我们想要的内容输出。这就是大部分模板引擎的思想,不过不同的模板引擎的语法是不同的。

2、语法

表达式

表达式名字语法用途
变量取值${…}获取请求域、session域、对象等值
选择变量*{…}获取上下文对象值
消息#{…}获取国际化等值
链接@{…}生成链接
片段表达式~{…}jsp:include 作用,引入公共页面片段

字面量

  • 文本值: ‘one text’ , ‘Another one!’ ,…
  • 数字: 0 , 34 , 3.0 , 12.3 ,…
  • 布尔值: true , false
  • 空值: null
  • 变量: one,two,… 变量不能有空格

文本操作

  • 字符串拼接: +
  • 变量替换: |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)

特殊操作

  • 无操作: _

传值: 在控制器类中通过加入Model参数,然后在跳转页面之前addAttribute添加参数

@RequestMapping("/test1")
public String test1(Model model){
    model.addAttribute("msg","thymeleat传值");
    // 返回的success会被视Thymeleaf视图解析器解析为 templates/success.html
    return "success";
}

取值: 在html页面中进行取值操作

使用 Thymeleaf 模板语言需要以 th: 为关键字开头,对参数进行操作

使用 th 关键字,需要在html标签之上添加 xmlns:th="www.thymeleaf.org" 命名空间

读取值还可以使用 [ [ ] ] 来对值进行解析,类似Vue中的差值表达式

这种好处就是当我们把该网页直接发给前端的时候,也能运行,只不过显示的是默认值【没有经过模板引擎的渲染】

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <div th:text="${msg1}">name</div>  //变量取值,取到了就将值赋给里面的文本值name,没有取到就使用name默认值
        <div th:utext="${msg2}"></div> 
         <!--从后台获取集合数据,通过循环遍历进行处理-->
        <h1 th:each="person : ${persons}"> [[${person}]] </h1>
    </body>
</html>

设置属性值-th:attr

  • 设置单个值:如下所示:分别给表单中的action属性、value属性重新设置了值,@#号的区别就是如表格所示。

    <form action="subscribe.html" th:attr="action=@{/subscribe}"> 
      <fieldset>
        <input type="text" name="email" />
        <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
      </fieldset>
    </form>
    
  • 设置多个值

    <img src="../../images/gtvglogo.png"  
         th:attr="src=@{/images/gtvglogo.png},title=#{logo},alt=#{logo}" />
    
  • 以上两个的代替写法 th:xxx 【xxx代表属性名】

    <input type="submit" value="Subscribe!" th:value="#{subscribe.submit}"/>
    
    <form action="subscribe.html" th:action="@{/subscribe}"> 
    

迭代

<tr th:each="prod : ${prods}">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>


<tr th:each="prod,iterStat : ${prods}" th:class="${iterStat.odd}? 'odd'">
    <td th:text="${prod.name}">Onions</td>
    <td th:text="${prod.price}">2.41</td>
    <td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

条件运算

<a href="comments.html"
	th:href="@{/product/comments(prodId=${prod.id})}"
	th:if="${not #lists.isEmpty(prod.comments)}">view</a>

<div th:switch="${user.role}">
      <p th:case="'admin'">User is an administrator</p>
      <p th:case="#{roles.manager}">User is a manager</p>
      <p th:case="*">User is some other thing</p>
</div>

属性优先级

image.png

3、初体验 Thymeleaf

1. 使用: 使用 Thymeleaf 模板语言直接引入其Starter场景即可

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

2、为什么引入相关场景即可使用?

  • 底层自动配置好了thymeleaf

    @Configuration(proxyBeanMethods = false)
    @EnableConfigurationProperties(ThymeleafProperties.class)
    @ConditionalOnClass({ TemplateMode.class, SpringTemplateEngine.class })
    @AutoConfigureAfter({ WebMvcAutoConfiguration.class, WebFluxAutoConfiguration.class })
    public class ThymeleafProperties {
        private static final Charset DEFAULT_ENCODING;
        public static final String DEFAULT_PREFIX = "classpath:/templates/";
        public static final String DEFAULT_SUFFIX = ".html";
        private boolean checkTemplate = true;
        private boolean checkTemplateLocation = true;
        private String prefix = "classpath:/templates/";
        private String suffix = ".html";
        private String mode = "HTML";
        private Charset encoding;
        private boolean cache;
        private Integer templateResolverOrder;
        private String[] viewNames;
        private String[] excludedViewNames;
        private boolean enableSpringElCompiler;
        private boolean renderHiddenMarkersBeforeCheckboxes;
        private boolean enabled;
        private final ThymeleafProperties.Servlet servlet;
        private final ThymeleafProperties.Reactive reactive;
    
        public ThymeleafProperties() {
            this.encoding = DEFAULT_ENCODING;
            this.cache = true;
            this.renderHiddenMarkersBeforeCheckboxes = false;
            this.enabled = true;
            this.servlet = new ThymeleafProperties.Servlet();
            this.reactive = new ThymeleafProperties.Reactive();
        }
    
  • 自动配好的策略

    • 所有thymeleaf的配置值都在 ThymeleafProperties
    • 配置好了 SpringTemplateEngine
    • 配好了 ThymeleafViewResolver
    • 我们只需要直接开发页面
  • 自动配置好了视图解析器

    public static final String DEFAULT_PREFIX = "classpath:/templates/";//模板放置处
    public static final String DEFAULT_SUFFIX = ".html";//文件的后缀名
    

4、Thymeleaf演示

1、编写一个控制层controller:

@Controller
public class ViewTestController {
    @GetMapping("/hello")
    public String hello(Model model){
        //model中的数据会被放在请求域中,相当于 request.setAttribute("a",aa)
        model.addAttribute("msg","一定要大力发展工业文化");
        model.addAttribute("link","http://www.baidu.com");
        return "success";
    }
}

2、/templates/success.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">  //插入名称空间有提示
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1 th:text="${msg}">nice</h1>  //变量取值【model里面取】,取到了就将值赋给里面的文本值nice,没有取到就使用nice这个文本值
<h2>
    <a href="www.baidu.com" th:href="${link}">去百度</a>  <br/>
    <a href="www.google.com" th:href="@{link}">去百度2</a>
</h2>
</body>
</html>

${link}:获取请求域中的link值
@{link}:拼接link的连接地址值【当成了要转到的超链接的网址就叫Link】

3、设置访问地址前置路径演示 @{/link} 的区别【非必要】

server:
  servlet:
    context-path: /world #设置静态资源访问路径应用名

这个设置后,URL要加上/app, 如http://localhost:8080/world/hello.html。 通过该地址进行访问,发现该link动态 的加上了前置路径,所以非常方便

image.png

5、Thymeleaf 帮助

指令

th:text		以普通文本形式接收值
th:utext	接收值后可以解析为html
th:each		遍历接收到的容器,集合数组等 ( 变量 : ${容器名} )

th:fragment="name"	将当前标签及子标签内的所有元素封装为一个组件(不影响当前页),可以在其他页面引用name
th:insert=""	引用的方式通过name使用其他页面封装的组件,一般作用在div中,然后组件会填充到div内部
th:replace=""	替换的方式通过name使用其他页面封装的组件,一般作用在div中,然后组件会将当前dib标签替换

各种取值 -- th 标识后才可以使用

${  }		表达式语句,可以书写表达式,例如if判断,三元运算,也可以获取传入的参数
@{/ }		表示超链接,在传参的时候不需要使用问好,需使用括号(key='value')
#{  }		国际化消息表达式,用来获取properties配置文件中的信息
~{ :: }		用来实现组件化信息,::的左侧用来填写组件所在页面,右侧填写组件的名称

Thymleaf 的工具类 -- #号开头

${#datas.format(date,str)}	时间格式化,按照指定格式输出data