`
mowengaobo
  • 浏览: 161302 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Spring MVC中如何通过 Checkbox 进行数据绑定 转

阅读更多

Spring MVC中如何通过 Checkbox 进行数据绑定

上一篇 / 下一篇  2009-11-27 23:43:24 / 个人分类:TechUsage

第一种方式:
<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中对应的数值


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics