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

Lassie ·
更新时间:2024-09-21
· 949 次阅读

在模板文件的表达式中,可以使用“${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>

浏览器访问:http://localhost:8080

页面输出:

HELLO WORLD 1
hello world 2

您可能感兴趣的文章:SpringBoot使用thymeleaf模板过程解析Spring Boot 2 Thymeleaf服务器端表单验证实现详解Spring Boot集成Thymeleaf的方法Spring Boot 整合 Shiro+Thymeleaf过程解析Spring Boot Thymeleaf实现国际化的方法详解SpringBoot引入Thymeleaf的实现方法SpringBoot thymeleaf eclipse热部署方案操作步骤Spring Boot集成Thymeleaf模板引擎的完整步骤



用java thymeleaf springboot JAVA 方法 静态 静态方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号