spring boot之thymeleaf(四)

由于spring boot不支持jsp,所以页面与后台交互就要使用其他的模板引擎可以使用Thymeleaf,Freemarke,Velocit等

spring boot推介的是Thymeleaf。

1.引入Thymeleaf模板引擎,Thymeleaf3+需要layout2+,Thymeleaf2+需要布局layout1+

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>

		<!--切换thymeleaf版本 -->
		<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
		<!-- 布局功能的支持程序 thymeleaf3主程序 layout2以上版本 -->

		<!-- thymeleaf2 layout1 -->
		<thymeleaf-layout-dialect.version>2.2.2</thymeleaf-layout-dialect.version>
	</properties>

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

2.Thymeleaf的使用

只要我们把HTML页面放在classpath:/templates/,thymeleaf就能自动渲染;

在html页面上方引入,就会有thymeleaf的语法提示

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

3.Thymeleaf的语法规则

4.Thymeleaf的一些表达式

Variable Expressions: ${...}:获取变量值;OGNL;
Selection Variable Expressions: *{...}:选择表达式:和${}在功能上是一样;
补充:配合 th:object="${session.user}:相当于用*表示了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;
      <script th:src="@{/static/js/test.js}"></script>
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)

遍历:th:each

    <table>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>年龄备注</th>
            <th>生日</th>
        </tr>
        <tr th:each="person:${userList}">
            <td th:text="${person.name}"></td>
            <td th:text="${person.age}"></td>
            <td th:text="${person.age gt 18} ? 你老了 : 你很年轻">18岁</td>
            <td th:text="${#dates.format(user.birthday, 'yyyy-MM-dd hh:mm:ss')}"></td>
        </tr>
    </table>

表单提交:th:field

	<form th:action="@{/th/postform}" th:object="${user}" method="post"
		th:method="post">
		<input type="text" th:field="*{name}" /> 
		<input type="text" th:field="*{age}" /> 
		<input type="submit" />
	</form>

猜你喜欢

转载自blog.csdn.net/BushQiang/article/details/80452548