当前位置:网站首页>Thymeleaf - learning notes

Thymeleaf - learning notes

2022-06-23 17:36:00 Slightly drunk CC

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 】

  1. 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 】

  1. 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>
原网站

版权声明
本文为[Slightly drunk CC]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231443286662.html