我用的ModelAttribute绑定对象在Spring Web应用程序。错误时,复选框值不会绑定到对象中?
一旦我注意到,如果对象具有布尔值A为真,如果我们取消选中A的复选框,则其值不会更新。
例如,我有具有属性“活动” =真一个课程对象。 在“编辑课程”视图中,我制作了一个复选框,该复选框绑定为“活动”。如果选中该复选框(绑定对象反映更改),事情就会正常运行,但如果我们取消选中复选框,则对象课程不会更改。
进一步的研究告诉我,那是因为复选框值可能不会通过浏览器提交的(这是一个在设计的HTML)。所以我必须使用丑陋的request.getParameter
来检查是否设置了该值。
我刚来this question,我发现asp.net mvc提供了一种更优雅的解决方法。我认为Spring必须提供类似的东西。有谁知道这是怎么做到的吗?
以下是我的代码:
控制器代码:
@RequestMapping(value="/test", method = RequestMethod.POST)
public String processEditLesson(@Valid Lesson lesson, BindingResult bindingResult, Model model) {
System.out.println("Lesson is active: " + lesson.isActive()); // still "true" even if the checkbox is unset
// Current work-around
String isActive = request.getParameter("active");
if (StringUtils.isNotNullOrEmpty(isActive)) {
lesson.setActive(true);
} else {
lesson.setActive(false);
}
...
}
查看代码:
<form id="lesson" class="EditorForm" action="${rc.getContextUrl('/test.html')}" method="post" >
<fieldset>
<legend><@spring.message code="lesson.edit"/></legend>
<@spring.formHiddenInput "lesson.id" />
<@spring.formHiddenInput "lesson.studio.id" />
<div class="Entry">
<label for="name"><@spring.message code="lesson.message"/></label>
<@spring.formInput "lesson.message" />
<span class="ErrorMessage"><@spring.showErrors "<br/>" /></span>
</div>
<input type="checkbox" name="active" checked="checked" />
<label for="active">${rc.getMessage('lesson.active')}</label>
<input type="submit" value="<@spring.message code='common.update' />" />
</fieldset>
</form>
谢谢,你怎么知道这种方式?我的意思是,我搜索了很多,但没有找到任何结果。只需稍加修改:我需要使用“_active”而不是“_lesson.active”来使其工作。 – 2012-01-04 08:48:40
我已更正名称。 - 我怎么知道的?我以专业的方式做了Spring MVC超过5年。当我开始这个问题时非常受欢迎。顺便说一句:如果您使用Spring复选框jsp标记,则隐藏的字段已包含在内。 – Ralph 2012-01-04 09:33:20
有用的信息。但是,我发现如果元素名称包含'.',则该值不会自动更改。我想我必须改变它使用JavaScript – abiieez 2013-06-18 14:47:25