如何将对象列表绑定到百万美元的复选框?

时间:2016-06-10 09:35:04

标签: java spring-mvc thymeleaf

我在使用对象列表绑定复选框输入时遇到了很多困难。问题是当我在输入字段类型复选框上添加 th:field =“* {userRole}”时,我正在获取在Web浏览器上作为响应的错误请求。

这是我的代码:

用户模型类:

public class User implements Serializable {
    private Integer id;
    private String username;
    private String password;
    private boolean enabled;
    private List<UserRole> userRole = new ArrayList<UserRole>(0);
}

UserRole Model类:

public class UserRole implements Serializable {
    @Id
    @GeneratedValue
    private Integer userRoleId;
    @ManyToMany(mappedBy = "userRole")
    private List<User> users;
    @Column(name = "role", nullable = false, length = 45)
    private String role;
}

模型属性:

@ModelAttribute(value = "user")
    public User userModel() {
        return new User();
}

GET方法:

@RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Map<String, Object> model) {
    List<UserRole> roles = roleService.getAllRoles();
    model.put("roles", roles);
    return "index";
}

我的POST方法:

@RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user") User userModel) {

}

索引页面表格:

<form role="form" action="#" th:action="@{/add}" th:object="${user}" method="post">

   <div class="form-group">
            <label for="email">User Name:</label>
            <input type="text" class="form-control" id="username"    th:field="*{username}" required autofocus>
   </div>
   <ul>
        <li th:each="item : ${roles}">
           <input type="checkbox" th:field="*{userRole}" th:value="${item}" />
           <label th:text="${item.role}">Test</label>
        </li>
    </ul>
    <input type="submit" value="Submit" />
</form>

当我点击提交时,浏览器显示为错误请求,但没有 th:field =“* {userRole}”我可以提交表单。有什么想法解决这个问题吗?

--- ---更新

问题是Thymeleaf无法直接绑定对象。因此添加了新的绑定字符串列表。

private List<String> userRoles = new ArrayList<>(0);

然后改变了@Roel提到的形式。

<li th:each="item, stat : ${roles}">
    <label th:text="${stat.index}">Test</label>
    <input type="checkbox" th:field="*{userRoles[__${stat.index}__]}" th:value="${item.userRoleId}" />
    <label th:text="${item.role}">Test</label>
</li>

感谢。

1 个答案:

答案 0 :(得分:3)

您正尝试将item作为值添加到List。这就像试图说ArrayList<Integer> list = 5;

您需要将项目添加到列表中:

    li th:each="item, stat : ${roles}">
       <input type="checkbox" th:field="*{userRole[__${stat.index}__]}" th:value="${item}" />
       <label th:text="${item.role}">Test</label>
    </li>

我不确定这是否能直接解决您的问题,因为百里香在将一个对象添加到列表时遇到了问题。 Thymeleaf通常使用字符串和整数等基本类型。但至少我指出了你的问题所在。尝试一下这一点。尝试使用这一行,至少这肯定会起作用:

 <input type="checkbox" th:field="*{userRole[__${stat.index}__].role}" th:value="${item.role}" />