java - 在 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>
解决方案
你这样做的方式应该是这样的:
控制器:
@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 格式输出。
推荐阅读
- azure - Azure DevOps 通用包 - 获取从外部源下载的工件版本
- google-cloud-platform - Gsutil 错误“捕获套接字错误,重试:超时”
- linux-kernel - #address-cells = <2> 情况的 DTC 编译错误
- debugging - Neovim 上的工作 pwa-chrome 类型启动 vimspector 配置是什么?
- php - 从数据库中获取值作为表
- arrays - 如何根据vue js中的数组唯一ID在选择选项中显示数据
- r - 逻辑回归输出建议
- node.js - 通过基于 nodejs 的微服务处理大量并行请求以修改 nosql 数据库中的许可证计数
- c++ - 编辑基于 Llvm 的项目时,Clang 代码模型在 qtcreator 中停止工作
- javascript - 如何在反应原生图像滑块框中更改图像大小