春季启动与Thymeleaf帖子列表

sil*_*b78 2 spring-mvc thymeleaf spring-boot

我想将一个字符串列表发布到我的控制器.但它始终只取第一个选定的值.

我的thymeleaf html表格:

<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>
Run Code Online (Sandbox Code Playgroud)

我的控制器:

@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";
}
Run Code Online (Sandbox Code Playgroud)

tho*_*paw 5

我认为你必须用特征来诠释特权

@RequestParam("privileges")
Run Code Online (Sandbox Code Playgroud)

它不是ModelAttribute,但是您从请求中收到它

编辑:两个SO线程,以更好地理解@RequestParam@ModelAttribute之间的区别.