java—如何在没有中间模型类的情况下将列表绑定到视图?

mrfwxfqh  于 2021-07-26  发布在  Java
关注(0)|答案(3)|浏览(330)

我有这个代码,工作得很好。
它从存储库中检索数据,将其设置为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设置为“watch”视图。
注意,在第一种情况下,它创建两个级别的“listplaces”,而在第二种情况下,它只创建一个级别。
所以它似乎缺少了第二个层次。
那么,这不能不需要中产阶级吗?
也许有一种方法可以在不需要中产阶级的情况下增加第二层次。

azpvetkf

azpvetkf1#

您没有显示所有相关的代码,但猜到了缺少的部分,需要时进行更改。一种选择是更改控制器方法,如:

@GetMapping("/myplaces")
public String whateverIsTheName(Model model) {
    model.addAttribute("listPlaces", placeRepository.selectPlaces(idUser));
    return "myplaces";
}

无需创建任何可以使用的中间类 Model 像上面一样,保持这两个级别,这样就有了一个对象 listPlaces .

omtl5h9j

omtl5h9j2#

你犯了个错误。在第一个控制器中,您将listplaces的对象绑定到modelandview。

ListPlaces listPlaces = new ListPlaces();
listPlaces.setListPlaces(placeRepository.selectPlaces(idUser));

ModelAndView modelAndView = new ModelAndView("/myplaces.html");
modelAndView.addObject("listPlacesBind", listPlaces);// Here listPlaces is an Object Of ListPlaces model

但是在第二个修改中,listplaces是一个列表而不是listplaces模型的对象,所以在html中它需要listplaces模型的对象,但是得到了一个列表,所以它显示了一个错误。

List<Place> listPlaces;
listPlaces = placeRepository.selectPlaces(idUser);

ModelAndView modelAndView = new ModelAndView("/myplaces.html");
modelAndView.addObject("listPlacesBind", listPlaces);// Here listPlaces is a list not an object of ListPlaces model

因此,更改html代码以接受列表,而不是对象。如果有任何疑问,请告诉我。

2j4z5cfb

2j4z5cfb3#

模型中不再存在名称listplaces,因为您现在将其命名为listplacesbind:

modelAndView.addObject("listPlacesBind", listPlaces)

也就是说,列表不再是模型中某个对象的字段,您必须按如下方式访问它:

<th:block th:each="place, itemStat : ${listPlacesBind}">                    
<span th:text="${listPlacesBind[__${itemStat.index}__].codPlace}" />

相关问题