【发布时间】:2021-01-16 14:19:14
【问题描述】:
我有这段代码可以正常工作。
它从存储库中检索数据,将其设置为 listPlaces 并将 listPlaces 绑定到视图。
控制器
ListPlaces listPlaces = new ListPlaces();
listPlaces.setListPlaces(placeRepository.selectPlaces(idUser));
ModelAndView modelAndView = new ModelAndView("/myplaces.html");
modelAndView.addObject("listPlacesBind", listPlaces);
型号
public class ListPlaces {
private List<Place> listPlaces;
public List<Place> getListPlaces() {
return listPlaces;
}
public void setListPlaces(List<Place> listPlaces) {
this.listPlaces = listPlaces;
}
}
查看
<th:block th:each="place, itemStat : *{listPlaces}">
<span th:text="*{listPlaces[__${itemStat.index}__].codPlace}" />
然后想到我可以通过执行以下操作来简化此代码:
- 移除 ListPlaces 模型类
- 将控制器代码更改为以下内容:
List<Place> listPlaces;
listPlaces = placeRepository.selectPlaces(idUser);
ModelAndView modelAndView = new ModelAndView("/myplaces.html");
modelAndView.addObject("listPlacesBind", listPlaces);
也就是说,不是在中间使用模型类,而是想尝试直接在控制器中创建列表并将其绑定到视图。
然后我收到以下错误:
Property or field 'listPlaces' cannot be found on object of type 'java.util.ArrayList' - maybe not public or not valid?
在调试模式下运行,我将 listPlaces 设置为“监视”视图。
注意到在第一种情况下它创建了两个级别的“listPlaces”,而在第二种情况下它只创建了一个级别。
看来它缺少第二级。
那么,如果不需要中间模型类就不能做到这一点吗?
也许有一种方法可以在不需要中产阶级的情况下添加第二层。
【问题讨论】:
标签: java spring spring-boot spring-mvc thymeleaf