SpringBoot_web开发-thymeleaf语法

我们看一下Thymeleaf的自动配置规则,我们得按照规则用起来,这里有一个自动配置,这里专门有一个thymeleaf,

Thymeleaf的自动配置,ThymeleafAutoConfiguration,自动配置不用看了,无非就是给里面添加一些组件,他有好多Thymeleaf2的,

但是判断不生效,视图解析器添加组件,我们主要看默认规则,默认规则都在ThymeleafProperties里面,来看什么默认规则呢,

@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";

照着他就直接用起来了,首先默认规则有一个默认的前缀,"classpath:/templates/",还有默认的后缀,前后缀就是我们视图

解析的代名词,然后也是通过它我们就知道,只要我们把html页面,放在类路径下的templates里面,然后thymeleaf就能够帮

我们自动渲染了,那我们就直接来看一下,比如我来写一个请求,如果我们以前写success,现在我们引入了thymeleaf模板引擎,

我们要去success页面,thymeleaf默认在这拼,相当于在类路径下的templates里面,给你找到success,还得拼一个后缀html

classpath:/templates/success.html

为了能达到目的地,我们就在这写一个success.html

我们来发送这个success请求,看我们的模板引擎是不是来到success页面

localhost:8080/success
package com.learn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {
	
	@ResponseBody
	@RequestMapping("/hello")
	public String hello1() {
		return "hello controller";
	}
	
	@RequestMapping("/success")
	public String success() {
		// classpath:/templates/success.html
		return "success";
	}
	
}
thymeleaf我们来参照他的文档

https://www.thymeleaf.org/

他这里有3.0.9版本和2.1.6版本,同时使用,这里也有对thymeleaf的简单介绍,它是现代的JAVA服务端的引擎

hymeleaf is a modern server-side Java template engine for both web and standalone environments.

特点是自然的模板语言,写法就比较像html的语法格式,我们主要来看他的文档

Thymeleaf 3.0

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.pdf

体会一下thymeleaf的使用,我们就以一个最常用的场景,比如我们要发success请求,来到这个页面,查出数据在页面展示,

如果是我们的JSP页面就简单多了,这个数据会放在我们请求域中,我想去success页面取值怎么取啊

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

如果是以前JSP,就直接${hello}就完事,现在不是JSP,要按照thymeleaf的语法来,他语法是什么就得来说一下,

首先我们要用thymeleaf,你得在html导入一个thymeleaf的名称空间,示例里面把这段复制

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

xmlns:th="http://www.thymeleaf.org"

当然你也可以不导,不导的话就没有语法提示了,导入的作用就是为了语法提示,我们使用的第一步,导入thymeleaf

的名称空间,第二步我们就可以使用thymeleaf的语法了,怎么使用呢,假设我这里有一个div,我们想在这里取出hello的值,

th:text,意思就是文本内容,${hello},来访问一下hello请求,看能不能取出来呢,我们来访问一下,发现也取出来了

http://localhost:8080/success
	@RequestMapping("/success")
	public String success(Map<String,Object> map) {
		// classpath:/templates/success.html
		map.put("hello", "您好");
		return "success";
	}
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>成功!</h1>
	<div th:text="${hello}"></div>
	
</body>
</html>
而且这样取值是有很大好处的,我们来给大家看一下,这是显示欢迎信息,如果这个页面不经过模板引擎解析,

来直接访问,这个显示的是前端自己写的数据,如果经过了模板引擎解析访问,把它就替换成后台的数据,这个前后端

分工起来就更好用了,接下来就详细来看一下thymeleaf的语法规则,thymeleaf的语法规则是什么样的呢
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>成功!</h1>
	<div th:text="${hello}">这是显示欢迎信息</div>
	
</body>
</html>
语法规则,首先就是第一个,th:text我们开始说,它是来改变我们当前元素里面的文本内容的,

我们可以用th任意属性,这个什么意思啊,由于前端好多东西都有默认值,比如这个div他有id,他有他的默认id,

叫div01,他还有他默认的class,我们就叫myDiv,而这些值我们想改怎么改呢,我都可以用th:id的方式,如果我们

能够取出一个值,比如${hello},然后th:class的方式,我都能改掉他的值,${hello},这就是我们使用th任意属性替换

原生属性的值,我们可以给大家看一下,id,class都是我们替换来的值
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>成功!</h1>
	<div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是显示欢迎信息</div>
	
</body>
</html>

所以我们有th任意属性,我们th语法到底有多少呢,我们可以参照一下官方文档,在官方文档的第10章,

属性的优先级,Attribute Precedence,这里列举了这些属性,那个是先执行,哪个是后执行,我们可以把它

截一个图,说一下每一个都是怎么用的

包括我们可以跟JSP类比一下,第一个叫Fragment inclusion,我们就叫片段包含,来做片段包含操作的,

一个是插入,一个是替换,就类似于jsp:include标签一样,我们抽取公共的片段,可以包含进来,然后第二个我们来看,

叫Fragment iteration,这个是我们来做遍历的,th:each,类似于jsp里面用的c:forEach,就是这个,th:if,th:unless,

th:switch,th:case是来做判断的,是来做条件判断的,条件判断就类似于以前的c:if等等,

这里还有一个Local variable definition,

做声明变量的,就类似于我们以前的c:set标签一样,可以来设置一些变量,还有一个General attribute modification,

这个是来做属性修改的,这个属性修改啊,他这里叫th:attr,th:attrprepend,th:attrappend,这是来做任意属性修改的,

我们以前来做属性修改,都是来替换值的,支持prepend,给他前面添加,给他append,给他后面来追加内容的,支持这些功能的,

还有一个是Specific attribute modification,这就是来修改我们指定属性的,就是修改我们默认的值,还有我们使用的th:text,

这个叫标签体里面文本内容的,这里有一个th:text,还有一个th:utext,一个是转义,一个是不转义,utext它是不转义,不转义

特殊字符,这样的话我们文本里面,H1标签就是一个大标题,但是上面的th:text它是转义的,相同的如果我们写了一个html片段,

用th:text展示出来,那片段就当成普通字符串了,才会给你在页面打印h1,但是不会给你转义特殊字符,还有个叫

Fragment specification,这个片段能够包含进来,就在这声明一下,我们后来再说就行了,那这个就是我们th的整个语法
但是我们再来看,在th里面呢,需要写一些表达式,表达式能写什么,我们能写th来做功能标签,

我们能写哪些表达式,我们官方文档里面也有说,这里有一个标准的表达式语法,有非常多的表达式语法,

给你来做一个简单的总结

But there are more types of expressions, and more interesting details to learn about the 
ones we already know. First, let’s see a quick summary of the Standard Expression 
features:

Simple expressions:
Variable Expressions: ${...}
Selection Variable Expressions: *{...}
Message Expressions: #{...}
Link URL Expressions: @{...}
Fragment Expressions: ~{...}
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: _
这些表达式语法我们来看一下,我们能写哪些表达式,${},*{},#{},@{},~{},这都是什么意思,

表达式语法,第一个${},我们之前是用来获取变量值的,每一个怎么用呢,每一个我们来参照文档来看一下,

标准表达式语法,Variables变量,${}是用来获取值,底层就是OGNL表达式,既然是OGNL

We already mentioned that ${...} expressions are in fact OGNL (Object-Graph Navigation Language) 

expressions executed on the map of variables contained in the context.

各种高大上的往下看,能怎么用呢,下面有各种例子,比如我们可以调用对象的属性,

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#variables

/*
 * Access to properties using the point (.). Equivalent to calling property getters.
 */
${person.father.name}

包括调属性的时候可以这样来使用

/*
 * Access to properties can also be made by using brackets ([]) and writing 
 * the name of the property as a variable or between single quotes.
 */
${person['father']['name']}

/*
 * If the object is a map, both dot and bracket syntax will be equivalent to 
 * executing a call on its get(...) method.
 */
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}

如果map中的key有空格,我们也可以这么来写,

/*
 * Indexed access to arrays or collections is also performed with brackets, 
 * writing the index without quotes.
 */
${personsArray[0].name}

数组中来取,

/*
 * Methods can be called, even with arguments.
 */
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

包括我们进行方法调用,包括方法我们还能给她传一个参数,这个就是我们OGNL表达式,不仅能调属性,获取对象的

属性,这是最基本的功能,然后他还能调用方法,接下来他还有一些功能,下面还有一个Expression Basic Objects,

我们表达式里边还能写"#.",#是内置的一些基本对象,使用内置的基本对象,内置的对象都是什么呢,

#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.

一个叫ctx,当前上下文对象,当前上下文的变量值,包括locale代表区域信息的,如果是WEB环境,有我们的request,response,

session,servletContext,它能够使用这几个内置对象,他还能用什么呢,包括内置对象怎么用,这一块也有文档,可以点进去,

Established locale country: <span th:text="${#locale.country}">US</span>.

如果我们要用我们国家的区域信息,哪个国家,区域代号,他的使用附录都在这,

You can read the full reference of these objects in Appendix A.

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-a-expression-basic-objects

比如我们获取请求参数的这个值,

/*
 * ============================================================================
 * See javadoc API for class org.thymeleaf.context.WebRequestParamsVariablesMap
 * ============================================================================
 */

${param.foo}              // Retrieves a String[] with the values of request parameter 'foo'
${param.size()}
${param.isEmpty()}
${param.containsKey('foo')}
...

通过size我们知道请求参数中有多少个参数,包括请求参数是不是为空一大堆,还有我们从session获取值,我来举一个例子,

例子都在附录里面,除了基本对象外,还有工具对象,Expression Utility Objects,内置的一些工具对象,工具对象会增强一些

功能,是哪个对象呢,

Besides these basic objects, Thymeleaf will offer us a set of utility objects that will 
help us perform common tasks in our expressions.

#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).

我们就来结合文档的演示,这个就是我们内置的工具对象,有演示在附录里打开,

You can check what functions are offered by each of these utility objects in the Appendix B.

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#appendix-b-expression-utility-objects

我们要使用numbers这个工具类,我们来做一些事情

/* 
 * Set minimum integer digits.
 * Also works with arrays, lists or sets
 */
${#numbers.formatInteger(num,3)}
${#numbers.arrayFormatInteger(numArray,3)}
${#numbers.listFormatInteger(numList,3)}
${#numbers.setFormatInteger(numSet,3)}

String工具类可以把他转成toString,

/*
 * Null-safe toString()
 */
${#strings.toString(obj)}  

下面也可以调用startWith方法,

/*
 * Check whether a String starts or ends with a fragment
 * Also works with arrays, lists or sets
 */
${#strings.startsWith(name,'Don')}                  // also array*, list* and set*
${#strings.endsWith(name,endingFragment)}           // also array*, list* and set*

有非常多的用法,这都有示例,我们都可以来对照使用,这个就是我们${},用的最多也是最强大的表达式,

接下来我们再来看第二个,叫*{},这个叫变量的选择表达式,这个东西是什么呢,

4.3 Expressions on selections (asterisk syntax)

*{}是什么呢,

Not only can variable expressions be written as ${...}, but also as *{...}.

不仅变量表达式可以写成${},还可以写成*{},他和${}在功能上是一样的,只是有一个补充功能,比如我们有一个tb:object,

我们取出一个对象,session里面取出user对象,我们先把tb:object对象重写,以后我们要用user对象的值,我们就可以在当前的

div里面,星号就代表我刚才的对象,然后我们直接获取对象里的属性就行了,这个就类似于写session.user.firstName

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

<div>
  <p>Name: <span th:text="${session.user.firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="${session.user.lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="${session.user.nationality}">Saturn</span>.</p>
</div>

补充使用就是,就是配合th:object一起使用的,以后我们要获取里面的值呢,就可以直接这么来做了,这个都有文档片段,

我们就参照这个文档,他都不难,我们就参照文档,我们来做就行了,我们再通过实验来深化使用,还有一个叫#{},这是干什么

呢,一个叫Message,Message它是来取国际化内容的,包括@{},它是来帮我们定义url链接的,用它定义url有什么好处呢,

我们可以在下面看到示例,比如这里就有一个示例,

<!-- Will produce 'http://localhost:8080/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" 
   th:href="@{http://localhost:8080/gtvg/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/details?orderId=3' (plus rewriting) -->
<a href="details.html" th:href="@{/order/details(orderId=${o.id})}">view</a>

<!-- Will produce '/gtvg/order/3/details' (plus rewriting) -->
<a href="details.html" th:href="@{/order/{orderId}/details(orderId=${o.id})}">view</a>

如果要传多个变量,

If several parameters are needed, these will be separated by commas:

@{/order/process(execId=${execId},execType='FAST')}

包括我们来看下面,前面都不写了,我们直接写一个杠,片段引用的表达式,我们文档里面也有Fragments,

我们要插入一个片段文档,我们要用~{},我们在实验里面再说,

<div th:insert="~{commons :: main}">...</div>

这就是我们五种表达式,如果要用thymeleaf模板引擎,知道何时用哪种表达式就行了,接下来就是其他的一些用法了,

你可以用字面量,比如普通的字符串,数字,包括多个数据用逗号隔开,文本操作,这里还有数学运算,他支持数学运算,

表达式里边就会用这些数学运算,包括还有布尔运算,什么并且什么,什么或什么,包括还支持比较运算,比如有一些

特殊字符,用后面这些来替代,条件运算,if-then,这个就是我们三元运算符,前面是一个条件
跟遍历有关Iteration,这一块我们看下面的示例,他这里有一段代码

https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#iteration

public void process(
        final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext servletContext, final ITemplateEngine templateEngine)
        throws Exception {
    
    ProductService productService = new ProductService();
    List<Product> allProducts = productService.findAll(); 
    
    WebContext ctx = new WebContext(request, response, servletContext, request.getLocale());
    ctx.setVariable("prods", allProducts);
    
    templateEngine.process("product/list", ctx, response.getWriter());
    
}

比如他用了一个Service查了一些数据,用prods保存起来,他用的是th:each标签,把我们要遍历的数据取出来${prods}

<!DOCTYPE html>

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

  <head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" 
          href="../../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  </head>

  <body>

    <h1>Product list</h1>
  
    <table>
      <tr>
        <th>NAME</th>
        <th>PRICE</th>
        <th>IN STOCK</th>
      </tr>
      <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>
    </table>
  
    <p>
      <a href="../home.html" th:href="@{/}">Return to home</a>
    </p>

  </body>

</html>

每一个数据要用什么变量名,他在冒号里面用了变量名,冒号后面要遍历的是集合,以后就用变量名取出这个数据,

那我们也来这么遍历,th:each每次遍历都会生成当前这个标签,我如果是这种遍历,

12 Inlining行内写法,我们就可以用[[...]] or [(...)]的方式,这两个有啥区别呢,其实[[...]]就是th:text,

[(...)]就是th:utext,

Expressions between [[...]] or [(...)] are considered inlined expressions in Thymeleaf, and inside 

them we can use any kind of expression that would also be valid in a th:text or th:utext attribute.

Note that, while [[...]] corresponds to th:text (i.e. result will be HTML-escaped), [(...)] 

corresponds to th:utext and will not perform any HTML-escaping. So with a variable 

such as msg = 'This is <b>great!</b>', given this fragment:

localhost:8080/success
package com.learn.controller;

import java.util.Arrays;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {
	
	@ResponseBody
	@RequestMapping("/hello")
	public String hello1() {
		return "hello controller";
	}
	
	@RequestMapping("/success")
	public String success(Map<String,Object> map) {
		// classpath:/templates/success.html
		map.put("hello", "<h1>您好</h1>");
		map.put("users", Arrays.asList("张三","李四","王五"));
		return "success";
	}
	
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>成功!</h1>
	
	<div id="div01" class="myDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是显示欢迎信息</div>
	<hr/>
	<div th:text="${hello}"></div>
	<div th:utext="${hello}"></div>
	<hr/>
	
	<!-- th:each每次遍历都会生成当前这个标签:3个h4 -->
	<h4 th:text="${user}" th:each="user : ${users}"></h4>
	<hr/>
	<h4>
		<span th:each="user : ${users}">[[${user}]]</span>
	</h4>
	
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值