How to use the tymeleaf template engine of spring boot? Case explanation

According to the notes of studying java in B station

Template engine Thymeleaf

The front end wants to display data. We used to convert pages into JSPS. In this way, we can realize data display and interaction. jsp supports very powerful functions, including the ability to write Java code. But we use the spring boot project in jar mode instead of war. We still use embedded Tomcat, but now spring boot does not support jsp by default. What should I use?
The second thing to note: the theory of light is not enough. In this free gift of 5 JAVA architecture project practical course and large factory interview question bank, interested can get into skirt 783802103, do not enter without foundation!

SpringBoot recommends that you use the template engine:

Template engine, we have heard a lot. In fact, jsp is a template engine. There are many freemakers, including the tymeleaf recommended by SpringBoot. There are many template engines, but their ideas are the same. What kind of ideas can we see in this picture

The role of the template engine is to use expressions to parse the background data.

Introducing Thymeleaf

How to introduce it? For springboot, everything is not a start. Let's introduce it into the project. Here are three websites:

Official website of Thymeleaf: https://www.thymeleaf.org/

Tymeleaf's homepage at Github: https://github.com/thymeleaf/thymeleaf

Official Spring document: find our corresponding version

https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

Find the corresponding pom dependency: you can enter the source code appropriately to see the original package!

Official website jar package
<dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
       </dependency>

Tymeleaf analysis

Previously, we have introduced Thymeleaf. How to use this?

First of all, we need to follow the automatic configuration principle of spring boot to see our automatic configuration rule of Thymeleaf. According to that rule, we will use it.

Let's go to the automatic configuration class of Thymeleaf: ThymeleafProperties

@ConfigurationProperties(prefix = "spring.thymeleaf")
public class ThymeleafProperties {

	private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

	public static final String DEFAULT_PREFIX = "classpath:/templates/";

	public static final String DEFAULT_SUFFIX = ".html";

We can see the default prefix and suffix in it!

We just need to put our html page under the templates under the classpath, and thmeleaf can help us render automatically.

You don't need to configure anything to use thmeleaf, just put it in the specified folder!

test

First write a TestController

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test1(){
        //Auto resolve to classpath:/templates/test.html
        return "test";
    }
}

Set up in template test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf Test page</title>
</head>
<body>
//I'm in
</body>
</html>

Run tests:

Thmeleaf syntax

To learn grammar, it's better to refer to the official website documents. Let's find the corresponding version;

Official website of Thymeleaf: https://www.thymeleaf.org/ Take a look at the official website! Let's download the official documents of tymeleaf!

Let's do the simplest exercise: we need to find out some data and show it on the page

1. Modify test request and add data transmission

@Controller
public class TestController {
    @RequestMapping("/test")
    public String test1(Model model){
        //Auto resolve to classpath:/templates/test.html
        model.addAttribute("msg","hello Thymeleaf!");
        return "test";
    }
}

2. We need to import namespace constraints first

We can go to the official document ා 3 to see the namespace

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

3. Write page

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf Test page</title>
</head>
<body>
//I'm in
<div th:text="${msg}"></div>
</body>
</html>

4. Test:

Usage syntax of Thymeleaf

1. We can use any th:attr to replace the value of the native attribute in Html!
2. Expression

Simple expressions:(Expression syntax)
Variable Expressions: ${...}: Get the variable value; OGNL;
    1),Get object properties, call methods
    2),Use built-in base objects:#18
         #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.

    3),Some built-in tool objects:
      #execInfo : information about the template being processed.
      #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.
==================================================================================

  Selection Variable Expressions: *{...}: Select expressions: and ${}It is the same in function;
  Message Expressions: #{...}: get international content
  Link URL Expressions: @{...}: definition URL;
  Fragment Expressions: ~{...}: Fragment reference expression

Literals(Literal)
      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:(Text operation)
    String concatenation: +
    Literal substitutions: |The name is ${name}|
    
Arithmetic operations:(***
    Binary operators: + , - , * , / , %
    Minus sign (unary operator): -
    
Boolean operations:(Boolean operation)
    Binary operators: and , or
    Boolean negation (unary operator): ! , not
    
Comparisons and equality:(Comparison operation)
    Comparators: > , < , >= , <= ( gt , lt , ge , le )
    Equality operators: == , != ( eq , ne )
    
Conditional operators:Conditional operation (ternary operator)
    If-then: (if) ? (then)
    If-then-else: (if) ? (then) : (else)
    Default: (value) ?: (defaultvalue)
    
Special tokens:
    No-Operation: _

Test:

Write controller

@Controller
public class TestController2 {
    @RequestMapping("/test1")
    public String test2(Map<String,Object> map){
        map.put("msg","<h1>Hello</h1>");
        map.put("users", Arrays.asList("qi","wuxin"));
        return "test";
    }
}

Test page

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>thymeleaf Test page</title>
</head>
<body>
I'm in
<!--Escape-->
<div th:text="${msg}"></div>
    <!--No escape-->
<div th:utext="${msg}"></div>
<!--ergodic-->
<h4 th:each="user: ${users}" th:text="${user}"></h4>
<!--In line writing-->
<h4 th:each="user: ${users}">[[${user}]]</h4>
</body>
</html>

Results page

Finally note: the theory of light is not enough. In this free gift of 5 JAVA architecture project practical course and large factory interview question bank, interested can get into skirt 783802103, do not enter without foundation!
The text and pictures of this article come from the Internet and my own ideas. They are only for learning and communication. They have no commercial use. The copyright belongs to the original author. If you have any questions, please contact us in time for handling

Tags: Java Thymeleaf Spring JSP

Posted on Thu, 04 Jun 2020 08:02:04 -0400 by papa