表单对象字段的默认值
我有一个表单,其中根据选择状态([checkboxOn/checkboxOff])应显示或不显示复选框。当显示该复选框时,默认情况下应选中它。
如何处理这种情况,考虑到
- 当 select 处于“checkboxOff”状态时 状态,我会 MyFormObject.isCheckboxOn == false;
- 当 select 处于 'checkboxOn' 状态时, 该值应该如要求的那样吗?
所有这些都应该适用于验证错误回发、显示新表单以及有效表单情况。
另外,我想避免在客户端使用 JavaScript。
这是一些需要扩展的代码:
class MyFormObject {
private String selectValue;
private boolean isCheckboxOn;
...
}
以及两个Spring控制器的方法:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView('/form.jsp', 'command', new MyFormObject());
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(BindingResult result, MyFormObject command) {
if (result.hasErrors()) {
return new ModelAndView('/form', 'command', command);
}
...
return new ModelAndView('redirect:/success.jsp');
}
I have a form where depending on the select state ([checkboxOn/checkboxOff]) a check box should appear or not. When the check box is displayed it should be checked by default.
How to handle that situation, taking into account that
- when select is in 'checkboxOff'
state, I would have
MyFormObject.isCheckboxOn == false; - when select is in 'checkboxOn' state,
the value should be as in request?
All of this should work also on Validation errors postback, and when new form is shown and on valid form case.
Also, I would like to avoid using JavaScript on client side.
Here is some code, which needed to be extended:
class MyFormObject {
private String selectValue;
private boolean isCheckboxOn;
...
}
and two Spring controller's method:
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
return new ModelAndView('/form.jsp', 'command', new MyFormObject());
}
@RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(BindingResult result, MyFormObject command) {
if (result.hasErrors()) {
return new ModelAndView('/form', 'command', command);
}
...
return new ModelAndView('redirect:/success.jsp');
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果要在 isCheckboxOn 设置为 false 时从视图中排除复选框字段,可以在 JSP 中用 ac:if 包围复选框字段:
要默认选中该框,可以使用 Spring 的表单标签库 直接绑定到复选框字段在模型中,或者您可以使用另一个
c:if
将checked
添加到您的标记中。
If you want to exclude the checkbox field from your view when isCheckboxOn is set to false, you can surround the checkbox field with a c:if in your JSP:
To check the box by default, you can use Spring's form tag library to bind directly to the checkbox field in the model, or you can use another
c:if
to add achecked
to your<input>
tag.