我使用ModelAttribute绑定Spring Web应用程序中的对象.
一旦我注意到,如果一个对象有一个布尔值A为真,如果我们取消选中A的复选框,它的值将不会更新.
例如,我有一个Lesson对象,其属性为"active"= true.在"编辑课程"视图中,我创建一个绑定到"活动"的复选框.如果选中复选框(绑定对象反映更改),则工作正常,但如果取消选中复选框,则对象课程不会更改.
进一步的研究告诉我,这是因为浏览器可能无法提交复选框值(这是HTML的设计).所以我必须使用丑陋request.getParameter来检查是否设置了值.
我刚刚提出这个问题,我看到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);
}
...
}
Run Code Online (Sandbox Code Playgroud)
查看代码:
<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" …Run Code Online (Sandbox Code Playgroud)