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

所属分类: 软件编程 / Java编程 阅读数: 52
收藏 0 赞 0 分享

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

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

更多精彩内容其他人还在看

SWT(JFace) 文本编辑器 实现代码

SWT(JFace) 文本编辑器 实现代码
收藏 0 赞 0 分享

SWT(JFace)小制作 BugTracker

SWT(JFace)小制作 BugTracker
收藏 0 赞 0 分享

SWT(JFace)小制作 FileBrowser文件浏览

SWT(JFace)小制作 FileBrowser文件浏览
收藏 0 赞 0 分享

SWT(JFace)体验之ProgressBar

SWT(JFace)体验之ProgressBar 实现代码。
收藏 0 赞 0 分享

SWT(JFace)体验之Slider,Scale

SWT(JFace)体验之Slider,Scale实现代码。
收藏 0 赞 0 分享

SWT(JFace)Group(分组显示)

SWT(JFace)体验之Group(分组显示)
收藏 0 赞 0 分享

SWT(JFace)体验之Sash(活动控件)

SWT(JFace)体验之Sash(活动控件)
收藏 0 赞 0 分享

SWT(JFace)体验之ViewForm的使用

SWT(JFace)体验之ViewForm的使用
收藏 0 赞 0 分享

SWT(JFace)体验之图片的动态渐变效果

SWT(JFace)体验之图片的动态渐变效果
收藏 0 赞 0 分享

浅谈将子类对象赋值给父类对象

浅谈将子类对象赋值给父类对象
收藏 0 赞 0 分享
查看更多