Controller:

@GetMapping("/access") public ModelAndView accessView() { ... modelAndView.addObject("newUser", new User()); 

User.class:

 @ManyToMany(...) private Set<Role> roles = new HashSet<>(); public User() { this.id = 1L; this.username = "1212121"; Role role1 = new Role(); role1.setId(1L); role1.setNameRole("QWERTY"); Role role2 = new Role(); role2.setId(2L); role2.setNameRole("ASDFGH"); Role role3 = new Role(); role3.setId(3L); role3.setNameRole("ZXCVBN"); this.roles.add(role1); this.roles.add(role2); this.roles.add(role3); }; 

Jsp page:

 <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> ... <form:form method='POST' ... modelAttribute="newUser"> ... <form:select path="roles" multiple="true" id="userRoles_" class="form-control"> <form:options items="${roles}" itemLabel="nameRole" itemValue="id"/> </form:select> 

I pass the User object, how to fill out form from the user’s collection on the page from the user role collection: select?

    1 answer 1

    In my opinion, you described form:options little incorrectly. In this case, the drop-down list does not know where exactly it should be roles , however, specifying the value of items as ${newUser.roles} , you specify where to get the values. In other words, there should be something like:

     <form:options items="${newUser.roles}" itemLabel="nameRole" itemValue="id" /> 

    However, I have a generally strange feeling that the list of roles is filled using the user’s domain model. It may make sense to use such a thing as @ModelAttribute and keep the model separate from the data. For example:

      @ModelAttribute("rolesList") public Set<Role> getRolesList() { Role role1 = new Role(); role1.setId(1L); ... Set<Role> roles = new HashSet<Role>(); roles.add(role1); roles.add(role2); roles.add(role3); return roles; } 

    Then filling the drop-down list on GET can be done like this:

    And User will be used in the form for further, say, saving.

    Hope this answers your question ... anyway.

    • "filling in the list of roles takes place using the domain model of a user" —not, it's just an example. Thank. - Artyom ... .- ....-.-