首页 > 解决方案 > 如何通过常量从数据模型中获取数据

问题描述

我正在使用Spring bootThymeleaf作为模板框架。我在后端设置了几个常量,我需要通过这些常量在前端获取数据。
我的后端如下所示:

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>

如何通过后端的常量访问模型数据?

标签: javaspringspring-bootspring-mvc

解决方案


你可以使用 **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>

推荐阅读