春天绑定列表<对象>形成:复选框 [英] Spring Binding List<Object> to Form:checkboxes

查看:255
本文介绍了春天绑定列表<对象>形成:复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法让我的形式绑定到复选框控制。我就在这里看了很多帖子,并尝试了一些技术,但没有运气。也许一套新的眼睛会有所帮助。

我的控制器:

 公共字符串editAccount(@RequestParam(ID)串ID,型号model){
    model.addAttribute(账户,accountService.getAccount(ID));
    model.addAttribute(allRoles,roleService.getRoles());
    返回EDIT_ACCOUNT;
}

我的jsp:

 <形式:形式行动=的ModelAttribute =帐户>
<形式:复选框项=$ {} allRoles路径=角色itemLabel =名itemValue =ID分隔符=< BR />中/>
< /表及GT;

生成的HTML:

 <跨度><输入ID =roles1NAME =角色类型=复选框值=1/><标签=roles1 >用户< /标签>< / SPAN><跨度>< BR /><输入ID =roles2NAME =角色类型=复选框VALUE =2/><标签=roles2>联系< /标签>< / SPAN><跨度>< BR /><输入ID =roles3NAME =角色类型=复选框VALUE =3在/&GT隐藏的名字=_角色值=/><标签=roles3INPUT TYPE =>超级管理员< /标签>< / SPAN&LT

我用于每个循环(未示出),以确保该模型对象包含的角色的第二。确实如此,但没有一个复选框被选中,当我提交角色对象始终是空的。有人可以告诉我,我缺少的是什么?

感谢

修改

不好意思才意识到它可能是有益的,看看帐户和作用对象:

 公共类账户{    私人字符串用户名,名字,姓氏,电子邮件;
    私人列表<的角色和GT;角色;    @NotNull
    @Size(分= 1,最大值= 50)
    公共字符串getUsername(){
        返回用户名;
    }    公共无效setUsername(字符串username){
        this.username =用户名;
    }    @NotNull
    @Size(分= 1,最大值= 50)
    公共字符串的getFirstName(){
        返回的firstName;
    }    公共无效setFirstName(字符串的firstName){
        this.firstName =名字;
    }    @NotNull
    @Size(分= 1,最大值= 50)
    公共字符串getLastName(){
        返回lastName的;
    }    公共无效setLastName(字符串的lastName){
        this.lastName = lastName的;
    }    @NotNull
    @Size(分钟= 6,上限= 50)
    公共字符串getEmail(){
        返回的电子邮件;
    }    公共无效setEmail(字符串email){
        this.email =电子邮件;
    }    公开名单<的角色和GT; getRoles(){
        返回的角色;
    }    公共无效setRoles(列表<的角色和GT;的角色){
        this.roles =角色;
    }    公共字符串的toString(){
        返回ReflectionToStringBuilder.toString(本);
    }}公共类角色{私人诠释身份证;
私人字符串名称;公共角色(){}公共角色(INT ID,字符串名称){
    this.id = ID;
    this.name =名称;
}公众诠释的getId(){
    返回ID;
}公共无效SETID(INT ID){
    this.id = ID;
}@NotNull
@Size(分= 1,最大值= 50)
公共字符串的getName(){
    返回名称;
}公共无效setname可以(字符串名称){
    this.name =名称;
}

}

编辑#2

控制器POST方法

  @RequestMapping(值=编辑,方法= RequestMethod.POST)
公共字符串updateAccount(@RequestParam(ID)字符串ID,@ModelAttribute(账户)@Valid AccountEditForm形式,BindingResult结果){
    的System.out.println(FORM值之后:+格式);
    回报(result.hasErrors()EDIT_ACCOUNT:ACCOUNT_REDIRECT?);
}

AccountEditForm是表单支持对象。当我做一个GET我抢帐户对象,并显示在屏幕前值传递到AccountEditForm。我会附上AccountEditForm仅仅是为了清楚。它是非常相似的帐户对象。我刚好从我的模型对象单独我的窗体对象。

 公共类AccountEditForm {    私人字符串用户名,名字,姓氏,电子邮件;
    私人列表<的角色和GT;角色=新的ArrayList<的角色和GT;();    @NotNull
    @Size(分= 1,最大值= 50)
    公共字符串getUsername(){
        返回用户名;
    }    公共无效setUsername(字符串username){
        this.username =用户名;
    }    @NotNull
    @Size(分= 1,最大值= 50)
    公共字符串的getFirstName(){
        返回的firstName;
    }    公共无效setFirstName(字符串的firstName){
        this.firstName =名字;
    }    @NotNull
    @Size(分= 1,最大值= 50)
    公共字符串getLastName(){
        返回lastName的;
    }    公共无效setLastName(字符串的lastName){
        this.lastName = lastName的;
    }    @NotNull
    @Size(分钟= 6,上限= 50)
    公共字符串getEmail(){
        返回的电子邮件;
    }    公共无效setEmail(字符串email){
        this.email =电子邮件;
    }    公开名单<的角色和GT; getRoles(){
        返回的角色;
    }    公共无效setRoles(列表<的角色和GT;的角色){
        this.roles =角色;
    }    公共字符串的toString(){
        返回ReflectionToStringBuilder.toString(本);
    }}

编辑#3角色属性编辑器

 公共类RolePropertyEditor扩展PropertyEditorSupport {    私人地图<整数,角色> roleMap =新的HashMap<整数,角色>();    公共RolePropertyEditor(列表<的角色和GT;的RoleList){
        对于(角色R:RoleList的)roleMap.put(r.getId(),R);
    }    公共无效setAsText(字符串incomingId){
        角色角色= roleMap.get(incomingId);
        的System.out.println(属性编辑器作用+角色);
        的setValue(作用);
    }    公共字符串getAsText(){
        的System.out.println(属性编辑器ID+((角色)的getValue())的getId());
        返回将String.valueOf(((角色)的getValue())的getId());
    }
}

定义在我的控制器,如:

  @InitBinder
公共无效initBinder(WebDataBinder粘合剂){
    binder.setAllowedFields(新的String [] {
            用户名,密码,confirmPassword,名字,姓氏,电子邮件,acceptTerms,currentPassword
    });
    binder.registerCustomEditor(Role.class,新RolePropertyEditor(roleService.getRoles()));
}

编辑#4新ProeprtyEditor

 公共类SecurityRolePropertyEditor扩展PropertyEditorSupport {    私人RoleService roleService;    公共SecurityRolePropertyEditor(RoleService roleService){
        this.roleService = roleService;
    }    公共无效setAsText(最终字符串名称){
        角色角色= roleService.getRoleByName(名);
        的setValue(作用);
    }
}


解决方案

添加equals方法,以你的角色的实体。

看到<一个href=\"http://stackoverflow.com/questions/6989711/spring-mvc-$p$p-populate-checkboxes/6996350#6996350\">answer (Spring MVC的pre填充复选框):类似的问题的更多细节。

I can't seem to get my form to bind to the checkboxes control. I read many posts on here and tried a few techniques but no luck. Maybe a fresh set of eyes will help.

my controller:

public String editAccount(@RequestParam("id") String id, Model model) {
    model.addAttribute("account", accountService.getAccount(id));
    model.addAttribute("allRoles", roleService.getRoles());
    return EDIT_ACCOUNT;
}

my jsp:

<form:form action="" modelAttribute="account">
<form:checkboxes items="${allRoles}" path="roles" itemLabel="name" itemValue="id" delimiter="<br/>"/>
</form>

the generated html:

<span><input id="roles1" name="roles" type="checkbox" value="1"/><label for="roles1">User</label></span><span><br/><input id="roles2" name="roles" type="checkbox" value="2"/><label for="roles2">Admin</label></span><span><br/><input id="roles3" name="roles" type="checkbox" value="3"/><label for="roles3">SuperAdmin</label></span<input type="hidden" name="_roles" value="on"/>

I used a second for each loop (not shown) to make sure that the model object contained the roles. It does, yet none of the checkboxes are checked and when I submit the roles object is always empty. Can someone please tell me what I'm missing?

Thanks

EDIT

Sorry just realized it might be helpful to see the account and role objects:

public class Account {

    private String username, firstName, lastName, email;
    private List<Role> roles;

    @NotNull
    @Size(min = 1, max = 50)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @NotNull
    @Size(min = 1, max = 50)
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @NotNull
    @Size(min = 1, max = 50)
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @NotNull
    @Size(min = 6, max = 50)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

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

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

    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }

}

public class Role {

private int id;
private String name;

public Role() {}

public Role(int id, String name) {
    this.id = id;
    this.name = name;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

@NotNull
@Size(min = 1, max = 50)
public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

EDIT #2

Controller Post Method

@RequestMapping(value = "edit", method = RequestMethod.POST)
public String updateAccount(@RequestParam("id") String id, @ModelAttribute("account") @Valid AccountEditForm form, BindingResult result) {
    System.out.println("FORM VALUES AFTER: " + form);
    return (result.hasErrors() ? EDIT_ACCOUNT : ACCOUNT_REDIRECT);
}

AccountEditForm is the form backing object. When I do a GET I grab an Account object and pass the values into an AccountEditForm before displaying the screen. I will attach the AccountEditForm just for clarity. It is very similiar to the account object. I just happened to seperate my form objects from my model objects.

public class AccountEditForm {

    private String username, firstName, lastName, email;
    private List<Role> roles = new ArrayList<Role>();

    @NotNull
    @Size(min = 1, max = 50)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @NotNull
    @Size(min = 1, max = 50)
    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    @NotNull
    @Size(min = 1, max = 50)
    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @NotNull
    @Size(min = 6, max = 50)
    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

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

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

    public String toString() {
        return ReflectionToStringBuilder.toString(this);
    }

}

EDIT #3 Role Property Editor

public class RolePropertyEditor extends PropertyEditorSupport {

    private Map<Integer, Role> roleMap = new HashMap<Integer, Role>();

    public RolePropertyEditor(List<Role> roleList) {
        for (Role r : roleList) roleMap.put(r.getId(), r);
    }

    public void setAsText(String incomingId) {
        Role role = roleMap.get(incomingId);
        System.out.println("PROPERTY EDITOR ROLE " + role);
        setValue(role);
    }

    public String getAsText() {
        System.out.println("PROPERTY EDITOR ID " + ((Role)getValue()).getId());
        return String.valueOf(((Role)getValue()).getId());
    }
}

Defined in my controller like:

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.setAllowedFields(new String[] {
            "username", "password", "confirmPassword", "firstName", "lastName", "email", "acceptTerms", "currentPassword"
    });
    binder.registerCustomEditor(Role.class, new RolePropertyEditor(roleService.getRoles()));
}

EDIT #4 NEW ProeprtyEditor

public class SecurityRolePropertyEditor extends PropertyEditorSupport {

    private RoleService roleService;

    public SecurityRolePropertyEditor(RoleService roleService) {
        this.roleService = roleService;
    }

    public void setAsText(final String name) {
        Role role = roleService.getRoleByName(name);
        setValue(role);
    }
}

解决方案

Add an equals method to your Roles entity.

see this answer (Spring MVC Pre Populate Checkboxes): of a similar question for more details.

这篇关于春天绑定列表&LT;对象&gt;形成:复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆