当前位置:网站首页>Thymeleaf - learning notes
Thymeleaf - learning notes
2022-06-23 17:36:00 【Slightly drunk CC】
Thymeleaf—— Learning notes
Reference resources / Excerpts from books : Organize yourself 、Spring Boot Of Web Development Writing ○ Crazy software
Refer to the picture : From the Internet / Offer yourself
explain : My relevant blog is only for reference !
One 、 Introduce
1.0 summary
How the template engine works : stay html Keep placeholders for dynamic data on the page ${xxx}, The template engine is responsible for parsing xxx, Find the server named xxx The data of , And replace the dynamic data ${xxx}.
Thymeleaf Is a heel Velocity、FreeMarker Similar templating engine , It's completely replaceable JSP . Compared to other templating engines , It has three attractive features :
1.Thymeleaf It can operate in both networked and non-networked environments , That is, it allows artists to view a static view of a page in a browser , You can also let programmers view dynamic page effects with data on the server . This is because it supports html Prototype , And then in html Add additional attributes to the tag to reach the template + How the data is presented . Browser interpretation html Undefined tag attributes are ignored , therefore thymeleaf Can be run statically ; When data is returned to the page ,Thymeleaf Tags dynamically replace static content , Make the page display dynamically .
2.Thymeleaf Out-of-the-box features . It provides standards and spring Standard two dialects , You can directly apply the template implementation JSTL、 OGNL Expression effect , Avoid daily templates 、 Change jstl、 Trouble with changing labels . Developers can also extend and create custom dialects .
3. Thymeleaf Provide spring Standard dialect and one with SpringMVC Perfectly integrated optional module , Form binding can be implemented quickly 、 Property editor 、 Internationalization and other functions .
1.1 introduce Thymeleaf
First, rewrite it as follows html label . In this way, it can be used in other labels th:* Such grammar .
<html xmlns:th="http://www.thymeleaf.org">
adopt xmlns:th="http://www.thymeleaf.org" Namespace , introduce Thymeleaf template engine , Convert static pages to dynamic pages . All elements that need to be dynamically processed should use th: The prefix .
1.2 introduce URL
Thymeleaf about URL The process is through grammar @{···} To deal with .
<link rel="stylesheet" th:href="@{/css/public.css}"/>
<script th:src="@{/js/time.js}"></script>
<a th:href="@{http://www.baidu.com/a.png}"> Absolute path </a>
<a th:href="@{/}"> Relative paths 【 stay Spring MVC The project is also equivalent to the root path of the project 】</a>
<a th:href="@{/css/jquery.css}"> Access the project root path static Under folder css The resource path under the folder </a>
1.3 expression
1.4 String manipulation
1.5 Operator
1.6 conditional
1.7 loop
1.8 Built-in objects
1.9 inline JS
//【HTML Code 】
<a href="javascript:;" id="toLogout" > sign out </a>
//【JavaScript Code 】
<!-- Be careful :javaScript Scripts need to use th:inline inline , Otherwise, the project path cannot be obtained -->
<script th:inline="javascript">
var conf = document.getElementById("toLogout");
conf.onclick = function (){
// Get the prefix of the website
var ctx = /*[[@{/}]]*/''; // It is also possible not to add two single quotation marks 【 If you don't add it, it will become popular, but it won't affect your acquisition 】
console.log(ctx)
// var ctx = [[${#httpServletRequest.getContextPath()}]];
if (confirm(" Confirm exit ?")){
//window.location.href : Jump
//window.location.replace : Method replaces the current document with a new document .
window.location.href="/admin/logout";
}
};
</script>
Two 、 Use
2.1 Spring MVC and Thymeleaf Integrate
2.1.1 Introduce dependencies (Spring MVC)
<!-- Spring5 and Thymeleaf Integrated package -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
2.1.2 To configure thymeleaf View parser
<!-- To configure thymeleaf View parser -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<!-- template engine -->
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<!-- Template parser -->
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
<!-- View prefix -->
<property name="prefix" value="/WEB-INF/templates/"/>
<!-- View suffix -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>
2.2 Spring Boot and Thymeleaf Integrate
Thymeleaf The most important class under the package is ThymeleafAutoConfiguration and ThymeleafProperties .
ThymeleafAutoConfiguration class What is needed for inheritance Bean Configure automatically , Include templateEngine and templateResolver Configuration of .
ThymeleafProperties class Read application.prpperties The configuration file , Set up Thymeleaf And default configuration .
2.2.1 application.yml The configuration file
# To configure thymeleaf
spring:
thymeleaf:
cache: false # close thymeleaf Template cache for 【 Turn off caching during development , Otherwise, you can't see the page in real time 】, Default on
encoding: UTF-8 # Template coding settings , The default is UTF-8
prefix: classpath:/templates/ # Set prefix , Default on classpath:/templates/ Under the table of contents
mode: HTML5 # The template pattern to apply to the template , The default is HTML
servlet:
content-type: text/html # write in HTTP Responsive Content-Type value . The default is text/html
2.2.2 pom.xml File to add thymeleaf rely on
<!-- Thymeleaf It depends on -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
x、 The application case
x.1 Variable expression
Variable expression namely OGNL expression or Spring EL expression ( stay Spring It's also called model attributes). for example :
<!-- Text substitution 【 The following two expressions are equivalent 】 -->
<span th:text="${session.loginUser.username}"> Zhang San </span>
<span>[[${session.loginUser.username}]]</span>
<!-- Attribute assignment / Traverse -->
<li th:each="user : ${userList}">
···
【 explain 】
- Thymeleaf Do not apply OGNL , It is SpringEL Implement variable expressions , So all
${}and*{}The expression will use Spring The expression engine of .
x.1.1 Radio button (th:field)
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label"> Gender </label>
<div class="col-sm-10">
<label class="checkbox-inline">
<input type="radio" name="sex" value=" male " id="sex1" th:field="${student.sex}"> male
</label>
<label class="checkbox-inline">
<input type="radio" name="sex" value=" Woman " id="sex2" th:field="${student.sex}"> Woman
</label>
</div>
</div>
x.1.2 Drop down options (th:each、th:value、th:text)
The situation a
<!-- The drop-down list shows 【th:each Traverse ${collegeList aggregate };th:value Give this option a value ;th:text Displays the value represented by the drop-down option 】 -->
<select class="form-control" name="collegeId">
<option th:each="item:${collegeList}" th:value="${item.collegeId}" th:text="${item.collegeName}"></option>
</select>
Scenario two
<!-- Automatically select... When processing drop-down list echo , Requirements :“ value 1”=“ value 2”【th:field=" value 1",th:value=" value 2"】 -->
<select class="form-control" name="teacherId" id="teacherid">
<option th:each="t:${teacherList}" th:value="${t.userId}" th:text="${t.userName}" th:field="${course.teacherId}"></option>
</select>
Scenario three
<!-- When th:field And the previous value This option is selected when the values in are equal -->
<select class="form-control" name="courseType" id="coursetype">
<option value=" required course " th:field="${course.courseType}"> required course </option>
<option value=" Elective courses " th:field="${course.courseType}"> Elective courses </option>
<option value=" Public class " th:field="${course.courseType}"> Public class </option>
</select>
x.2 URL relevant
<!-- Static resources should be enclosed in single quotation marks -->
<a th:href="@{
'/bookOperation/toUpdateView/'+${b.bid}}"> modify </a>
<a onclick="deleteBook()" th:href="@{
'/bookOperation/bookDelete/'+${b.bid}}"> Delete </a>
<!-- Create a new form , Used for holding POST To DELETE request -->
<form id="postToDelete" action="" method="post">
<!-- take post The request is converted to the specified request method DELETE, With the help of HiddenHttpMethodFilter Filter handle post The request is automatically converted to DELETE request 【 Pay attention to norms 】 -->
<input type="hidden" name="_method" value="DELETE" />
</form>
<script> // Process delete operation function deleteBook(){
var flag = confirm(" Delete this book ?"); if (flag){
//event.preventDefault() Is to tell the browser not to perform the default action associated with the event 【 The default hyperlink jump action is canceled here 】 event.preventDefault(); var postToDelete = document.getElementById('postToDelete'); // Get the jump path in the delete button hyperlink , And assign it to postToDelete Form action attribute postToDelete.action = event.target.href; // Form submission postToDelete.submit(); } } </script>
x.3 form Form submission (th:action)
<form class="form-horizontal" role="form" th:action="@{/admin/updateCourse}" id="searchForm" method="post">
<!-- hold PSOT Request conversion to PUT request 【 To adapt to RESTFUL style 】(post and get Request not to write this code ) -->
<input type="hidden" name="_method" value="PUT">
<!-- Hide the field storage page number -->
<input type="hidden" name="pageNum" id="currentPage" value="1">
<!-- Echo search keywords -->
<input type="text" class="form-control" placeholder=" Please enter a name " id="keyword" name="userName" th:value="${studentQueryVo.userName}"/>
<span class="input-group-addon btn" id="sub" onclick="fetchData(1)"> Search for </span>
</form>
<script> // Submit Form , Display the data list in pages function fetchData(num) {
$('#currentPage').val(num); $('#searchForm').submit(); } </script>
x.4 Dynamic transfer parameters
( scene 1) Paging bar transfer parameters
<!-- 【 One 】GET Style biography -->
<!-- thymeleaf send out GET When requesting parameters , Use ( Parameter name 1=value1, Parameter name 2=value2,...) To express ;-->
<a th:href="@{/emp/list(pageNum=${num},pageSize=${size})}" th:text="${num}" />
<!-- The above code is equivalent to :/emp/list?pageNum=1&pageSize=3 -->
<!-- 【 Two 】REST Style biography -->
<a th:href="@{
'/user/list/'+${n}+'/4'}" th:text="${n}"></a>
<!--【 The above example is to send paging parameters 】-->
【 Be careful 】
- When splicing address parameters , Use single quotation marks for static addresses “
' Static parameters '” Lead up , Then use the plus sign “+” Splicing dynamic parameters ;
x.5 Operator
x.5.1 Gender discrimination
<!--【 How to write it 1】 -->
<td th:text="${emp.gender==0?' Woman ':' male '}"></td>
<!--【 How to write it 2】 -->
<td th:text="${emp.gender}==0?' Woman ':' male '"></td>
边栏推荐
- 千呼万唤,5G双卡双通到底有多重要?
- Analysis of three battery capacity monitoring schemes
- How to choose an account opening broker? Is it safe to open an account online now?
- Look, this is the principle analysis of modulation and demodulation! Simulation documents attached
- 创新技术领航者!华为云GaussDB获颁2022年云原生数据库领域权威奖项
- Jetpack compose and material you FAQs
- 你的PCB地线走的对吗?为什么要有主地?
- [network communication -- webrtc] analysis of webrtc source code -- supplement of pacingcontroller related knowledge points
- 单火线设计系列文章10:拓展应用-单火开关实现双控
- Postgresql_ Optimize SQL based on execution plan
猜你喜欢
![[untitled] Application of laser welding in medical treatment](/img/c5/9c9edf1c931dfdd995570fa20cf7fd.png)
[untitled] Application of laser welding in medical treatment

What does the timestamp 90K mean?

微信小程序:酒店预计到店日期的时间选择器

Intel arc A380 graphics card message summary: the entry-level price products of running point and bright driving need to be optimized

Robot Orientation and some misunderstandings in major selection in college entrance examination

How to configure MySQL log management

Jetpack compose and material you FAQs
![[30. concatenate substrings of all words]](/img/e7/453c8524a23fbb7501e85140547ce1.png)
[30. concatenate substrings of all words]
![[go]沙盒环境下调用支付宝扫码支付](/img/d4/c6d72a697bc08f69f11121a15109b3.png)
[go]沙盒环境下调用支付宝扫码支付

以 27K 成功入职字节跳动,这份《 软件测试面试笔记》让我受益终身
随机推荐
WebSocket能干些啥?
EasyPlayer移动端播放webrtc协议时长按播放页面无法关闭“关于我们”页面
根据年份获取第一天和最后一天
QT当中的【QSetting和.ini配置文件】以及【创建Resources.qrc】
解析 | 模-数(A/D)转换器
Google Play Academy 组队 PK 赛,火热进行中!
Intranet penetration token stealing
Talk about the difference between redis cache penetration and cache breakdown, and the avalanche effect caused by them
华为手机通过adb安装APK提示“签名不一致,该应用可能已被修改”
Elk log collection system deployment
Get first and last days by year
Jetpack Compose 与 Material You 常见问题解答
The official Chinese course of zero foundation introduction jetpack compose is coming
《MPLS和VP体系结构》
酒店入住时间和离店时间的日期选择
How to configure MySQL log management
What are the inductance parameters? How to choose inductance?
JMeter stress testing tutorial
Is your PCB ground wire right? Why should we have a master land?
ctfshow php的特性