Thymeleaf common syntax: the expression in the template file calls the static method of the Java class

In the expression of the template file, you can use the format "${T (fully qualified class name). Method name (parameter)}" to call the static method of the Java class.

Development environment: IntelliJ IDEA 2019.2.2
Spring Boot version: 2.1.8

Create a new Spring Boot project named demo.

1.
Add the Thymeleaf dependency to pom.xml

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

2、src/main/java/com/example/demo/TestUtils.java

package com.example.demo;

public class TestUtils {
    public static String toUpperCase(String s){
        return s.toUpperCase();
    }
}

3、src/main/java/com/example/demo/TestController.java

package com.example.demo;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestController {
    @RequestMapping("/")
    public String test(){
        return "test";
    }

    public static String toLowerCase(String s){
        return s.toLowerCase();
    }
}

4、src/main/resources/templates/test.html

<div th:text="${T(com.example.demo.TestUtils).toUpperCase('hello world 1')}"></div>
<div th:text="${T(com.example.demo.TestController).toLowerCase('HELLO WORLD 2')}"></div> 

Browser access: http://localhost:8080
page output:
 

HELLO WORLD 1
hello world 2

 

Guess you like

Origin blog.csdn.net/gdjlc/article/details/102595423