springboot2整合thymeleaf模板引擎

1 什么是thymeleaf

  • Thymeleaf是用于Web和独立环境的现代服务器端Java模板引擎。
  • Thymeleaf的主要目标是将优雅的自然模板带到您的开发工作流程中—HTML能够在浏览器中正确显示,并且可以作为静态原型,从而在开发团队中实现更强大的协作。Thymeleaf能够处理HTML,XML,JavaScript,CSS甚至纯文本。

2 使用方法

2.1 在pom.xml中导入thymeleaf的依赖

<dependency>
		<groupId>org.springframework.bootgroupId>
    	<artifactId>spring-boot-starter-thymeleafartifactId>
dependency>

2.2 使用thymeleaf的语法编写html文件

我在这里用了bootstrap优化页面的展示效果

2.2.1 编写html文件

  • 通过查看ThymeleafProperties.java文件,可知Thymeleaf的默认配置的前缀为classpath:/templates/,后缀为.html
    springboot2整合thymeleaf模板引擎_第1张图片
  • 项目中存放html文件的路径
    springboot2整合thymeleaf模板引擎_第2张图片

2.2.2 html文件源码


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>testtitle>
    <link rel="stylesheet" th:href="@{/css/bootstrap.min.css}" href="../../static/css/bootstrap.min.css"/>
head>
<body class="container">
<br>
<div class="panel panel-info">
    <div class="panel-heading">
        <h3 class="panel-title">商户h3>
    div>
    <div class="panel-body">
        <div th:object="${merchant}">
            <p class="text-primary">姓名:<span th:text="*{name}">span>p>
            <p class="text-primary">年龄:[[*{age}]]p>
        div>
    div>
div>
<table class="table table-striped">
    <thead>
    <tr>
        <th>#th>
        <th>idth>
        <th>名称th>
        <th>价格th>
    tr>
    thead>
    <tbody>
    <tr th:each="product : ${products}">
        <td th:text="${productStat.count}">td>
        <td th:text="${product.id}">td>
        <td th:text="${product.name}">td>
        <td>[[${product.price}]]td>
    tr>
    tbody>
table>

body>
html>

2.3 controller层的源码

  • 将我们需要展示的数据放入到Model中,thymeleaf引擎就会从中取出数据进行展示
@Controller
public class ProductController {

    @GetMapping("/product/list")
    public String listProducts(Model model) {
        List<Product> products = new ArrayList<>();
        products.add(new Product(1001, "手机", 3999.00));
        products.add(new Product(1002, "电脑", 8999.00));
        products.add(new Product(1003, "鼠标", 59.99));
        products.add(new Product(1004, "键盘", 499.99));
        model.addAttribute("products", products);

        model.addAttribute("merchant", new Merchant("布特", 33));

        return "product/list.html";
    }
}

2.4 效果展示

2.4.1 直接通过浏览器打开html文件

springboot2整合thymeleaf模板引擎_第3张图片

2.4.2 使用thymeleaf引擎解析过的html文件

springboot2整合thymeleaf模板引擎_第4张图片

2.5 源码地址

源码地址:码云

3 thymeleaf语法

3.1 语法规则

th:任意HTML属性,来替换原生属性的值
springboot2整合thymeleaf模板引擎_第5张图片

3.2 表达式语法

3.2.1 变量表达式 ${…}

	获取变量值,实际上就是OGNL表达式
	
	获取对象的属性和调用方法
	使用内置的基本对象
		#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.
	
	内置的一些工具对象
		#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).

3.2.2 选择表达式 *{…}

和${}在功能上是一样,例如:

<div th:object="${session.user}">
    <p>Name: <span th:text="*{firstName}">Sebastianspan>.p>
    <p>Surname: <span th:text="*{lastName}">Pepperspan>.p>
    <p>Nationality: <span th:text="*{nationality}">Saturnspan>.p>
div>

3.2.3 消息表达式 #{…}

获取国际化内容

3.2.4 连接URL表达式 @{…}

定义URL,例如

<a th:href="@{/list(id=${#request.getParameter('id')})}">返回a>

3.2.5 片段引用表达式 ~{…}

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

3.2.6 标签体表达式

thymeleaf支持直接在标签体中展示数据,语法:[[${...}]][[*{...}]]

3.2.7 其它常用表达式

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

你可能感兴趣的:(springboot)