我是Spring Boot和Thymeleaf的新手,并且希望将Java代码中定义的变量的值传递给HTML页面。我搜索了Web,但可能已经监督了一些重要的事情。我尝试使用以下代码进行操作:
Favorite.java
:
@Getter
@Setter
public class Favorite {
private String id;
private String target;
public Favorite(final String id, final String target) {
setId(id);
setTarget(this.target);
}
}
PortalController.java
:
public class PortalController {
private final List<Favorite> myFavorites = new ArrayList<>();
@ModelAttribute("myFavorites")
public List<Favorite> myFavorites() {
if (myFavorites.size() == 0) {
myFavorites.add(new Favorite("ZEMPLOYEE_WORKTIME_ZWD_ESS_ABW", "ABC"));
myFavorites.add(new Favorite("ZEMPLOYEE_WORKTIME_CATS", "DEF"));
myFavorites.add(new Favorite("ZEMPLOYEE_WORKTIME_PEP_WISH_PLAN", "XYZ"));
}
return myFavorites;
}
index.html
:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" lang="de" xml:lang="de">
<head>
[…]
</head>
<body>
[…]
<ul>
<div th:switch="${not #lists.isEmpty(myFavorites)}" th:utext="${myFavorites}">
<div th:case="true">
<div th:each="myFavorite : ${myFavorites}">
<li>
<td th:text="${myFavorite.id}"></td>
<td th:text="${myFavorite.task}"></td>
</li>
</div>
</div>
<div th:case="*">
Nothing to show!
</div>
</div>
</ul>
[…]
我得到了“没什么可显示的!”文本,表示myFavorites
为空。我想念什么或误解了什么?
编辑:
我在读取PortalController
后修改了The @ModelAttribute in Depth:
public class SpbPortalController {
private final List<Favorite> myFavorites = new ArrayList<>();
private final Map<String, List<Favorite>> favoritesMap = new HashMap<>();
@RequestMapping(value = "/getMyFavorites", method = RequestMethod.POST)
public String submit(@ModelAttribute("myFavorites") final List<Favorite> favorites,
final BindingResult result, final ModelMap model) {
if (result.hasErrors()) return "error";
model.addAttribute("myFavorites", favorites);
favoritesMap.put(favorites.toString(), favorites);
return "favoritesView";
}
@ModelAttribute
public void getMyFavorites(final Model model) {
if (myFavorites.size() == 0) {
myFavorites.add(new Favorite("ZEMPLOYEE_WORKTIME_ZWD_ESS_ABW", "ABC"));
[…]
model.addAttribute("myFavorites", myFavorites);
}
[不幸的是,我仍然遗漏或误解了某些内容,因此网页仍然显示“ Nothing to show!”。
根据documentation @ModelAttribute应该与@RequestMapping一起使用。您可以找到有关此批注如何工作的更详细说明here。