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; @Controllerpublic 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 1hello world 2

thymeleaf中调用Java方法

将需要调用的类进行注册便可以在thymeleaf中进行调用

Java 代码

@Component("module")
public class ModuleService {
	private final BizSiteInfoService siteInfoService;
	private final BizArticleService bizArticleService;
	// some codes...
	public Object get(String moduleName) {
        switch (moduleName) {
            //热门文章
            case "hotList":
                return bizArticleService.hotList(CoreConst.PAGE_SIZE);
            //网站信息统计
            case "siteInfo":
                return siteInfoService.getSiteInfo();
        }
    }
}
12345678910111213141516

tymeleaf代码

获取对象

<div>文章总数:<span th:text="${@module.get('siteInfo').articleCount}"></span></div>
1

获取列表

<ol class="article-list">
    <li th:each="item,temp:${@module.get('hotList')}"  class="slide">
        <span th:text="${temp.index+1}"></span>
        <a th:text="${item.title}" th:href="${'/blog/article/'+item.id}"></a>
    </li>
</ol>
123456
posted @   xiondun  阅读(554)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示