空间管理 您的位置: 软工博客首页 » lianggt08的个人空间 » 日志 Spring MVC中如何通过 Checkbox 进行数据绑定 上一篇 / 下一篇 2009-11-27 23:43:24 / 个人分类:TechUsage 查看( 7 ) / 评论( 0 ) / 评分( 0 / 0 ) 第一种方式: <c:forEach items= "${myFormBean.customerList}" var= "cust" varStatus= "status" > <c:out value = "${customerList.customerName}" / > <form.:checkbox path= "customerList[${status.index}].customerPremiumPaid" / > < /c:forEach> 注:其中form.:checkbox中的path指明了使用formbean中的那个对象的值进行绑定 绑定的规则如下: 对于Map类型的集合,[ ]运算符可以通过三种形式指定的key匹配Command对象中Map类型集合对应的元素: mapping[key].number mapping['key'].number mapping["key"].number 对于与Map类型对应的表达式中的[ ]运算符所接受的参数不同,对于List或者Array类型的集合,[]运算符现在接受的是索引值(index)而不是key list[0].number array['1'].number list["2"].number 如: <input type="text" name="phoneNumbers[0].number"/> 第二种方式: <spring:bind path="command.myBooleanProperty"> <input type="hidden" name="_<c:out value="${status.expression}"/>"> <input type="checkbox" name="<c:out value="${status.expression}"/>" value="true" <c:if test="${status.value}">checked</c> 采用普通checkbox时,一定不要忘记上面红色部分。红色部分的目的在于当checkbox在提交时未选中时进行数据绑定,会将其对应的false值绑定到其对应的checkbox中。因为在提交form请求时,form只会把选中的checkbox值传过来并进行绑定,未选中的checkbox通过其对应的前缀带有“_”的hiden域进行“候补”绑定。 Spring官方的解释为: If the checkbox has not been ticked therefore not sending a parameter back in the request, then spring automatically looks at the '_' prefixed hidden field and grabs the value from that. 另外需要注明的是,使用formbean中的数据进行表现层绑定的组件,都一定要位于form之中,这样才能够在提交的时候更新formbean中对应的数值