【问题标题】:unable to bind data using spring data functionality无法使用弹簧数据功能绑定数据
【发布时间】:2012-09-10 09:09:00
【问题描述】:

线程继续sending-data-back-to-controller-spring-mvc

我正在开发一个产品详细信息页面,我需要向用户显示一些选项,用户将选择其中的几个选项,并且在提交按钮上,产品应该被添加到购物篮中。 我的意图是将该数据对象传输到我的购物车控制器,以便我可以使用这些值,并且由于该对象包含动态值,因此无法定义预先确定的字段对象。 这是我的数据对象

public class PrsData {
    private Map<String, List<PrsCDData>> prsCDData;

    public PrsData(){
        this.prsCDData = MapUtils.lazyMap(new HashMap<String, List<PrsCDData>>(),
        FactoryUtils.instantiateFactory(PrsCDData.class));
    }
} 

public class PrsCDData {
    private Map<String, List<ConfiguredDesignData>> configuredDesignData;
    // same lazy map initialization
}

在我的产品详细信息页面控制器中,我将值设置为:

model.addAttribute("prsData", productData.getPrsData());

在我的产品详细信息页面 JSP 上,我的表单中有这个:

<form:form method="post" commandName="prsData" action="${addProductToCartAction}" >
    <form:hidden path="prsCDData[''${prsCDDataMap.key}'']
                    [${status.index}].configuredDesignData['${configuredDesignDataMap.key}']
                    [${configuredDesignDataStatus.index}].code" />
</form:form>

但是当我点击提交按钮时,我得到了以下异常

org.springframework.beans.InvalidPropertyException: 
    Invalid property 'prsCDData['Forced'][0]' of bean class [com.product.data.PrsData]: 
        Property referenced in indexed property path 'prsCDData['Forced'][0]' 
        is neither an array nor a List nor a Set nor a Map; 
        returned value was [com.product.data.PrsCDData@6164f07e]

我不确定我在哪里做错了,因为在产品详细信息页面上,这些隐藏字段被正确绑定并且甚至分配了值,但是当提交表单时我遇到了这个问题。

【问题讨论】:

    标签: java spring jsp spring-mvc jstl


    【解决方案1】:

    LazyMap 工厂必须返回一个 LazyList。

    给定的工厂 FactoryUtils.instantiateFactory(PrsCDData.class) 创建一个新的 PrsCDData 对象,而不是一个 PrsCDData 列表。

    prsCDData['Forced'] -> if exists then return it else create instance of PrsCDData.class
    

    应该是

    prsCDData['Forced'] -> if exists then return it else create instance of LazyList<PrsCDData>
    

    使用 LazyList,因为您想立即访问索引“0”,否则会导致 ArrayIndexOutOfBoundsExecption

    编辑:简单示例

    public class Test {
    
    @SuppressWarnings("unchecked")
    public static void main(String[] args) throws UnsupportedEncodingException {
    
        Map<String, List<SimpleBean>> map = MapUtils.lazyMap(new HashMap<String,List<Object>>(),new Factory() {
    
            public Object create() {
                return LazyList.decorate(new ArrayList<SimpleBean>(), FactoryUtils.instantiateFactory(SimpleBean.class));
            }
        });
    
        System.out.println(map.get("test").get(0));
    }
    
    public static class SimpleBean {
        private String name;
    }
    
    }
    

    【讨论】:

    • +1 确实很好地发现了错误,会尝试这个并会更新,但对我来说,这似乎是 99% 的问题
    猜你喜欢
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2021-12-30
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多