java - 如何通过常量从数据模型中获取数据
问题描述
我正在使用Spring boot
和Thymeleaf
作为模板框架。我在后端设置了几个常量,我需要通过这些常量在前端获取数据。
我的后端如下所示:
public class Constant {
public static final String MY_VAR = "test";
}
@Controller
public class MyController {
@GetMapping("/")
public String home(Model model) {
List<String> data = new ArrayList<>();
data.add("item1");
model.addAttribute(Constant.MY_VAR, data);
return "home";
}
}
在前端我想这样做:
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div class="container-fluid p-0">
<div th:unless="${not #lists.isEmpty(Constant.MY_VAR)}">
</div>
</div>
</body>
</html>
如何通过后端的常量访问模型数据?
解决方案
你可以使用 **ModelAndView ** 来解决这个问题
- 后端
@GetMapping("/")
public ModelAndView home() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("home");
List<String> data = new ArrayList<>();
data.add("item1");
modelAndView.addObject("test", data);
return modelAndView;
}
- 前端
<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
<div class="container-fluid p-0">
<div th:if="${test.size() > 0}">
<li th:each="item:${test}">
<span th:text="${item}"></span>
</li>
</div>
</div>
</body>
</html>
推荐阅读
- javascript - 如何为多个 HTML 文件调用一个 JavaScript 文件?
- swift - Xcode Swift - WKWebView 实现
- typescript - 访问私有构造函数
- signals - 带 LimeSDR IQ 分路器相移的 GnuRadio
- vba - VBA中变量名的变量值
- javascript - 刷新计时器在达到 0 时显示文本,而不是继续负倒计时
- .net-core - Visual Studio 2019 中的 .NET Core - 桌面部署选项
- python - 如何在 Python 中创建范围列表?
- reactjs - 如何在 Muidialog 中禁用 MuiBackdrop(材料 UI 反应)
- java - 如何创建独立的 TestNG Maven 可执行文件