【问题标题】:How to bind Spring form:checkbox instead of form:checkboxes?如何绑定 Spring form:checkbox 而不是 form:checkboxes?
【发布时间】:2015-10-05 20:00:13
【问题描述】:

我在使用 form:checkbox 时遇到问题。我不能让它显示选定的值。当我选择值并提交时,正确的值会显示在数据库中。当我加载页面时,所有值(复选框)都没有被选中。

下面的元素位于这个里面:

<form:form role="form" commandName="user" class="form-horizontal" action="${form_url}">
</form:form>

这很好用:

<form:checkboxes items="${availableRoles}" path="roles" itemLabel="role" itemValue="id" element="div class='checkbox'"/>                    

这不起作用:

<c:forEach items="${availableRoles}" var="r" varStatus="status">
    <div class="checkbox">
        <form:checkbox path="roles" label="${r.description}" value="${r.id}"/>
    </div>
</c:forEach>

这是我的域类:

public class User {
    private List<Role> roles;

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

这是我的自定义属性编辑器:

public class RolePropertyEditor extends PropertyEditorSupport {

    @Override
    public void setAsText(String text) {
        Role role = new Role();
        role.setId(Integer.valueOf(text));
        setValue(role);
    }

}

控制器有这个方法:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(Role.class, new RolePropertyEditor());
}

控制器方法:

@RequestMapping(value = "/update/{userId}", method = RequestMethod.GET)
public String updateUser(@PathVariable Integer userId, Model model) {
    User user = userService.getByUserId(userId);
    List<Role> availableRoles = roleService.getAllRoles();

    model.addAttribute("availableRoles", availableRoles);
    model.addAttribute("user", user);

    return "user/update";
}

【问题讨论】:

    标签: spring checkbox data-binding spring-form


    【解决方案1】:

    调试会话后我找到了解决方案。

    由于 Spring 内部,JSP 应该如下所示:

    <c:forEach items="${availableRoles}" var="r">
        <div class="checkbox">                          
            <form:checkbox path="roles" label="${r.description}" value="${r}"  />
        </div>
    </c:forEach>
    

    注意 value 是 item (r),而不是像 r.id 这样的 item 成员。

    您还需要在您的自定义 PropertyEditor 中实现 getAsText。

    @Override
    public String getAsText() {
        Role role = (Role) this.getValue();
        return role.getId().toString();
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 2019-11-05
      • 2017-03-19
      • 1970-01-01
      • 2012-06-21
      • 1970-01-01
      • 1970-01-01
      • 2019-08-21
      相关资源
      最近更新 更多