Java xiaobai practice manual-fourth stage-Thymeleaf

table of Contents

Thymeleaf

Introduction to Thymeleaf

What is Thymeleaf

Why use Thymeleaf

Start using Thymeleaf

The first Thymeleaf program

HTML template creation

Import Thymeleaf

Writing Thymeleaf

running result

Precautions for using Thymeleaf

Thymeleaf operating principle

Thymeleaf template

Thymeleaf uses ideas

Text replacement

th:text 

th: utext

Text replacement summary

Link replacement

th:src

th:href

Element deletion

th:remove

Context save reference|use type

Get the value of the object in the Context

Conditional judgment

th:if

Set iteration

th:each


Thymeleaf

 

Introduction to Thymeleaf


What is Thymeleaf

  • Thymeleaf is an HTML template engine|engine
  • The function is to use an HTML file as a template, and modify or replace the content in the template according to the specific tags in the template, and finally form a new HTML
     


Why use Thymeleaf

  • Now we use Servlet to receive requests submitted by users, but using Servlet to output response content is very troublesome
  • If you write an HTML as a template; use Thymeleaf to modify or replace the specified content, and then output this page, then you can respond to a complex page

Start using Thymeleaf


The first Thymeleaf program

  • First write an HTML file as a template
  • Import the jar package of Thymeleaf
  • Write code, create a template engine to load HTML templates and output the results


HTML template creation

The template code is as follows:


< !DOCTYPE html>
<!-- 一定要注意htm1标签中的属性,必须添加--> 
<html xmIns="http:/ /www . W3. org/1999/ xhtml"
    xm1ns : th="http: / /wWw . thymeleaf .org">
<head>
    <meta http-equiv="Content - Type" content= "text/html;
    charset=utf-8">
    <title> Thymeleaf</title>
</head>
<body>
    <!--这里的th:text="${msg}" 后续会讲解-->
    <div th:text=" ${msg}" >文本内容</div>
</body>
< /html> 


Import Thymeleaf

Write coordinates in pom file


<dependency>
    <groupId>org.thymeleaf</groupId>
    <artifactId> thymeleaf< /artifactId>
    <version>3.0.10.RELEASE</version>
</dependency>


Writing Thymeleaf

Write the following code in the main method


//实例化模板引擎
TemplateEngine templateEngine=new TemplateEngine();
/ /实例化模板分析器
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
/ /设定分析时的字符集
resolver . setCharacterEncoding( "utf-8");
/ /模板弓|擎加载分析器
templateEngine. setTemplateResolver(resolver);

 

//创建上下文对象,用于替换模板中的文字
Context ctx = new Context( ) ;
/ /设置msg值为Hello World!!!
ctx. setVariable("'msg","He1lo World!!!");
//套用模板引擎,返回字符串
String result = templateEngine . process("index.html", ctx);
System . out . println(result);

running result

After running the above code, you will see the following output in the console

< !DOCTYPE html>
<html xmlns="http: //www . W3. org/1999/ xhtml">
    <head>
        <meta http- equiv= "Content - Type" content= "text/html; charset=utf-8">
        <title>Thymeleaf</title>
    </head>
    <body>
        <div>Hello World!!!</div>
    </body>
</html>
 

Precautions for using Thymeleaf

  • HTML tag attributes in HTML template files must be written in accordance with regulations
  • All related classes in the java code are imported from the org.thymeleaf package
  • The index.html file in the above example is under src/main/java of the maven project 

Thymeleaf operating principle

  • Java uses the Thymeleaf template engine to first read the HTML template into java, and then modify or replace the part with " th: " in the template according to the specific meaning with the corresponding content in the Context object
  • There are many "th:" parts in Thymeleaf, and the specific meaning of each will be introduced in the detailed explanation of Thymeleaf
     

Thymeleaf template

Thymeleaf uses ideas

 

  • The idea of ​​using Thymeleaf is to add th attributes of specific functions to the HTML template without deleting the content of the HTML template. These th attributes generate HTML code according to specific functions when the template is parsed.
  • Using Thymeleaf development, in principle, HTML template pages can be directly executed after Servlet processing. The content displayed is based on static HTML templates and modified from it.
  • We want to learn the most commonly used th attributes and their functions


Text replacement

th:text

The code in the HTML template is as follows


<!-- 没有编写th属性--> 
<div>Hello< /div>
<!-- 编写了th:text -->
<div th:text=" ${msg}">Hello</div> 
<!-- 编写了th:text并且其中有字符-->
<div th:text="'信息: '+${msg}" >Hello</div>

 

Servlet code is as follows


String str="<p>第一 段</p><p>第二 _段</p>";
Context ctx=new Context( );
ctx. setVariable("msg", str);
ThymeleafHelper . ThymeleafWrite("index",response,ctx);

The results are as follows

  

th: utext

The code in the HTML template is as follows


<!--没有编写th属性--> 
<div>Hello< /div>
<!-- 编写了th:text -->
<div th:utext="${msg}" >Hel1o</div>
<!-- 编写了th:text并且其中有字符-->
<div th:utext="'信息: '+${msg}" >He11o< /div> 

Servlet code is as follows 


String str="<p>第一 段</p><p>第二 段</p>";
Context ctx=new Context();
ctx. setVariable("msg",str);
ThymeleafHelper . ThymeleafWrite(" index", response, ctx);

 The results are as follows

  

Text replacement summary

th:text is to display the content directly on the page, if the content contains html, the page will not be parsed
th:utext is to parse the htm code in the content and display it on the page
 


Link replacement

th:src

  • An HTML element can have both the src attribute and the th:src attribute
  • When running the HTML template, the src attribute takes effect, and when Thymeleaf is parsed, th:src will take effect
  • Before writing a link in th:src, you must use @{} to wrap the path
  • Th: src can use placeholders with custom names and assign values ​​to the placeholders
     
//页面中有如下代码
<img src=" img1. png" th:src= "@{img2.png}" />
//占位符使用( num是自定义的名称)
<img src= ”img1. png" th:src= "@{ img{num} . png(num=2)}" />
//为占位符赋值可以是表达式(Context对象中保存着:键n值2)
<img src=" img1. png" th:src= "@{ img{num} . png(num=${n})}" />
//占位符可以是多个
<img src= " img1. png
    th: src="@{ img{ num}. {type }(num=${n},type='png')}"/>
//上面所有 代码Thymeleaf解析后生 成的都是
<img src= " img2.png" />


th:href

  • An HTML element can have both href attribute and th:href attribute
  • When running the HTML template, the href attribute takes effect, and when Thymeleaf parses it, th: href will take effect
  • Before writing a link in th:href, you must use @{} to wrap the path
  • You can use custom name placeholders in th:href, and assign values ​​to the placeholders
     
//页面中有如下代码
<a href-" index . html" th:href="@{ index . do}">链接</a>
//Thymeleaf解析后生成
<a href="index . do" >链接</a>
//URL需要传递信息的链接(一个或多个)
<a href=" index . html" th: href= "@{index . do(a=1, b=2)}" >链接</a>
//Thymeleaf解析后生成
<a href=" index. do?a=1&amp ;b=2" >链接</a>
//URL需要传递信息的链接的信息来自Context对象(键n值1)
<a href=" index . html" th: href= "@{index . do(a=${n}, b=2)}">链接</a>
//Thymeleaf解析后生成
<a href=" index . do?a=1&amp; b=2" >链接</a>


Element deletion

th:remove

The th:remove attribute can ignore specified elements when Thymeleaf is parsed so that the generated html does not contain them

  • 1. all: delete the label and all the children.
  • 2. Body: does not contain mark deletion but delete all its children.
  • 3.tag: contains the deletion of the tag, but does not delete its children.
  • 4.all-but-first: delete all children containing tags except the first one.
  • 5.none: do nothing. This value is useful for dynamic evaluation.

Use th: remove="all" to help everyone understand, the HTML template code is as follows


<ul>
    <li >孙悟空</li>
    <li>猪八戒</ li>
    <li th: remove= "all">刘备</li>
    <li>唐三藏</li>
</ul>
//Thymeleaf解析后生成
<ul>
    <li >孙悟空</li>
    <li>猪八戒</ li>
    <li>唐三藏</li>
</ul>

Context save reference|use type

Get the value of the object in the Context
 

  • Sometimes we add to the Context object, the saved content is an object, such as an entity class object
  • To get the attribute value of the saved entity class object on the page, you need to use "  . " In the expression to call
  • Note that the get method of the entity class is actually called here, but you can write the attribute value directly when writing.
     

 Note:

The User class object u is saved in the Context object, which contains the name attribute value tom, and I want to get the
name attribute value:


<div th: text="${u.name}">名字</div> 
    //Thymeleaf解析后生成
<div>tom< /div>


Conditional judgment

th:if

In the homepage, if you have logged in, the user name will be displayed, if you have not logged in, the login link will be displayed, u is the user entity class, the code is as follows


<div th:if="${u! =null}" th:text=" '欢迎您:'+${u. name}" >欢迎您:[用户名]</div>
<div th:if="${u==null}" >
    <a href="login. html" th :href="@{login. do}">登录</a>
</div>
///当用户已经登录时Thymeleaf解析后生成
<div >欢迎您: tom</div>
//当用户尚未登录时Thymeleaf解析后生成
<div ><a href="login. do" >登录</a></div>


Set iteration
 

th:each

  • We often query a collection in Servlet and want to display the contents of the collection on the page
  • The number of elements in the collection is usually not one. We need to iterate over each element
  • Thymeleaf provides th:each to realize the iteration of the collection
  • The basic format th:each ="[ custom name ] : $ {[ Collection in Context ]}"
  • The part replaced by the iteratively generated content in the html template can be set to th:remove= "all"
     

  

A user list generated by collection iteration, list is a collection of Context users, the code is as follows


<ul>
    <li th:each=" user : ${list}" th:text="${user .name}">曹操</li>
    <li th: remove="al1" >孙权</li>
    <li th: remove="all">刘备</li> 
    <li th: remove="all">诸葛亮</li>
</ul>
//Thymeleaf解析后生成
<ul>
    <li>孙悟空</1i>
    <li>猪悟能</li>
    <li>沙悟净</1i>
</ul> 

 

Guess you like

Origin blog.csdn.net/c202003/article/details/106978247