华域联盟 JAVA Springboot Thymeleaf模板文件调用Java类静态方法

Springboot Thymeleaf模板文件调用Java类静态方法

在模板文件的表达式中,可以使用“${T(全限定类名).方法名(参数)}”这种格式来调用Java类的静态方法。

开发环境:IntelliJ IDEA 2019.2.2

Spring Boot版本:2.1.8

新建一个名称为demo的Spring Boot项目。

1、pom.xml

加入Thymeleaf依赖

    <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>

浏览器访问:localhost:8080

页面输出:

HELLO WORLD 1
hello world 2

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持华域联盟。

本文由 华域联盟 原创撰写:华域联盟 » Springboot Thymeleaf模板文件调用Java类静态方法

转载请保留出处和原文链接:https://www.cnhackhy.com/311.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部