2

I want to post a list of strings to my controller. But it always only take the first selected value.

my thymeleaf html form:

<form action="/add" method="post">
    <div class="form-group">
        <label for="roleId">ID</label> <input type="text" class="form-control" id="roleId" name="id" required="required" />
    </div>
    <div class="form-group">
        <label for="rolePrivileges">Privileges</label>
        <select class="form-control" id="rolePrivileges" name="privileges" multiple="multiple" size="10" required="required">
            <option th:each="type : ${privilegesList}" th:value="${type}" th:text="${type}">Privilege</option>
        </select>
    </div>
    <button type="submit" class="btn btn-default">Create</button>
</form>

my controller:

@RequestMapping(value = "/add", method = RequestMethod.POST)
public String addSomething(Model model, @ModelAttribute("id") String id,
        @ModelAttribute("privileges") List<String> privileges) {
    // add something with a service
    return "redirect:/roles";
}
silb78
  • 139
  • 2
  • 11

1 Answers1

5

I think you have to Annotate the privilges with

@RequestParam("privileges")

It is not a ModelAttribute but you receive it from the request

Edit: two SO threads to better understand the difference between @RequestParam and @ModelAttribute.

Community
  • 1
  • 1
thopaw
  • 3,796
  • 2
  • 17
  • 24