【问题标题】:How to use a List as a Model Attribute in Spring?如何在 Spring 中使用列表作为模型属性?
【发布时间】:2019-04-25 18:58:08
【问题描述】:

我的 Home 控制器是这样的:

    @RequestMapping("/")
    public ModelAndView welcome(@ModelAttribute("myValuesInRows") List<String> myValuesInRows,  ModelMap model) {
        List<Spravochnik> dropDown = spravochnikService.findAll("sprav_of_spravs");
        List<String> justValuesInRows = new ArrayList<>();
        for(Spravochnik sprav : dropDown) {
            for(List<String> vals : sprav.getValuesInRows()) {
                for(String v : vals) {
                    justValuesInRows.add(v);
                }
            }
        }
        for(int i=1; i<justValuesInRows.size(); i+=2) {
            myValuesInRows.add(justValuesInRows.get(i));
        }
        model.addAttribute("myValuesInRows", myValuesInRows);
        return new ModelAndView("home", model);
    }

我的主页视图有这个我正在使用的选择:

<f:form>
<f:select path="myValuesInRows" items="${myValuesInRows}" name="tableName" id="tableName">
</f:select>
</f:form>

当我尝试显示它时,Spring 显示此错误:

No primary or default constructor found for interface java.util.List.

我想将我的选择连接到我正在传递的这个列表,这里是如何完成的?

【问题讨论】:

    标签: java spring forms binding


    【解决方案1】:

    使用实现List 的类之一,例如ArrayListLinkedList,它们具有默认构造函数。

    @ModelAttribute("myValuesInRows") ArrayList<String> myValuesInRows
    

    您可以在此处找到List 的所有已知实现类的列表:

    https://docs.oracle.com/javase/8/docs/api/java/util/List.html

    【讨论】:

    • 我编辑了我的代码,现在出现了一个新错误:Invalid property 'myValuesInRows' of bean class [java.util.ArrayList]: Bean property 'myValuesInRows' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
    • @Nikrango 你能分享一些我可以测试的 github repo 或类似的东西吗?
    • 另一方面,您可以尝试在model 中传递列表,而不是作为单独的参数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    相关资源
    最近更新 更多