Achieve change user roles scenario with an application

63 Views Asked by At

I have a scenario which i need to update user role which 1 user can have m roles.

@Entity
public class User{
    private String name;
    private String login;
    private String password;
    @OneToMany
    private Role role;
}

So suppose I have the List of User objects with the roles associate with each User. Now i have to display those data in the UI. For example like below,

User Name      Roles
A              (ckbox_selected)Admin (ckbox)Viewer (ckbox)Reporter
B              (ckbox)Admin          (ckbox)Viewer (ckbox_selected)Reporter

User A has currently admin privilege and now we add viewer too. So how can this kind of scenario achieved in view and service layer? The dao will return List of Users. Or is there any other easy way design and achieve such kind of scenario?

Can explain using Spring MVC context or any other framework if not. View can either jsp's with spring tags or other template view such as Apache Velocity etc. The model is mapped with database using hibernate.

1

There are 1 best solutions below

0
On

it should be smth like this

Entity

@Entity
public class User{
    private String name;
    private String login;
    private String password;
    @OneToMany
    private List<Role> roles;
}

JSP with spring mvc tags

<form:form comandName="user" method="post">

<form:checkboxes path="roles" items="${roles}" itemLabel="name" itemValue="id"/>

</form:form>

Spring controller

    @RequestMapping(method = RequestMethod.POST)
    public String add(@ModelAttribute("user") User user, BindingResult result) {
        validator.validate(user, result);
        if (result.hasErrors())
            return "/user";

        userDao.update(user);
        return "redirect:/users";

    }

  @InitBinder
  public void initBinder(ServletRequestDataBinder binder) {
  binder.registerCustomEditor(List.class, "roles", new CustomCollectionEditor(List.class) {

            protected Object convertElement(Object element) {
                if (element != null) {
                    Integer roleId = Integer.parseInt(element.toString());
                    Role role = (Role) roleDao.getById(roleId);
                    return role;

                }
                return null;
            }

        });

    }