首页 > 解决方案 > 在 Thymeleaf 中调用 Java 类

问题描述

如何使用 Thymeleaf 引用 Java 类?我正在尝试在网站上显示我的 Java 类的结果。当我使用 Spring Boot 显示 Java 类的输出时它可以工作,当我使用 Spring Boot 显示 Thymeleaf HTML 模板时它也可以工作,但是我现在被困在如何从 Thymeleaf HTML 中调用 java 类代码。

Spring Boot 应用程序文件

package net.javavatutorial.tutorials;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootExampleApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootExampleApplication.class, args);
    }
}

控制器文件

package net.javavatutorial.tutorials;

import org.springframework.stereotype.Controller;    
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/")
class MainController
{
    @RequestMapping(method = RequestMethod.GET)
    ModelAndView
    index()
    {
        ModelAndView mav = new ModelAndView("index");
        mav.addObject("version", "0.1");
        return mav;
    }
}

Filewalk.java接受目录路径并输出该目录中包含的文件

package net.javavatutorial.tutorials;

import java.io.File; 

public class Filewalk {
    
    public static String filewalk(String s) {
        String result = "";
        // creates a file object
        File file = new File(s);
        
        // returns an array of all files
        String[] fileList = file.list();
        
        for (String str : fileList) {
            result += str + "\n";
        }
        
        return result;
    }
}

我要在其中显示 Filewalk.java 输出字符串的Index.HTML文件

<!DOCTYPE html>
<html>
   <head>
      <meta charset = "ISO-8859-1" />
      <link href = "css/styles.css" rel = "stylesheet"/>
      <title>Spring Boot Application</title>
   </head>
   <body>
      <h4>Thymeleaf Spring Boot web application</h4>
   </body>
</html>

标签: javaspringspring-bootspring-mvcthymeleaf

解决方案


你这样做的方式应该是这样的:

控制器:

@RequestMapping(method = RequestMethod.GET)
public ModelAndView index() {
    ModelAndView mav = new ModelAndView("index");
    mav.addObject("version", "0.1");
    mav.addObject("filewalk_results", Filewalk.filewalk("directory"));
    return mav;
}

HTML:

<!DOCTYPE html>
<html>
  <head>
      <meta charset = "ISO-8859-1" />
      <link href = "css/styles.css" rel = "stylesheet"/>
      <title>Spring Boot Application</title>
  </head>

  <body>
      <h4>Filewalk results:</h4>
      <pre th:text="${filewalk_results}" />
  </body>
</html>

您进行所有实际计算并创建对象/信息以放在您的模型上,然后以 HTML 格式输出。


推荐阅读