我正在努力解决一些 thymeleaf 问题 - 我正在尝试创建表单来编辑保存在 mysql 数据库中的现有用户。我想要实现的是表单中的复选框列表,我可以在其中看到选中的角色(根据数据库中的信息),并可以通过选中/取消选中其他角色来更改它们。
查看:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
<meta charset="UTF-8"></meta>
<title>User edit</title>
</head>
<body>
<form
th:action="@{/edit/{id}/{username}/user(username=${user.username}, id=${user.id})}"
method="post">
<div>
<label> User name : <input type="text" name="username"
placeholder="username" />
</label>
</div>
<div>
<label> User password : <input type="text" name="password"
placeholder="" />
</label>
</div>
<form:checkboxes items="${rolesList}" path="roles" />
<div>
<input type="submit" value="Save" />
</div>
</form>
</body>
</html>
Controller 方法:
@GetMapping(path="/edit/{id}/{username}/user")
public String editSpecificUser(Model model, @PathVariable Long id, @PathVariable String username ) {
User user = userRepository.findById(id);
List<Role> rolesList = roleRepository.findAll();
model.addAttribute("user", user);
model.addAttribute("rolesList", rolesList);
return "edituser";
}
用户类别:
@Entity(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false, unique = true)
private String username;
private String password;
private int enabled;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles;
最佳答案
标签
<form:checkboxes items="${rolesList}" path="roles" />
用于 JSP 模板中,而 Thymeleaf 有自己的基于 HTML 的标签系统(带有 Thymeleaf 独有的附加标签),默认情况下不使用 JSP 标签。
您想要实现的目标可以类似于下面的代码来完成。您必须更改它,以便它与您的 Role
类匹配。我使用了一个简单的类,其名称为 String 对象,并且有一个与其检查的角色相对应的 boolean 值。
<ul>
<li th:each="role : ${rolesList}">
<label th:for="${role.name}" th:text="${role.name}">Role name</label>
<input type="checkbox" th:id="${role.name}"
th:name="${role.name}" th:checked="${role.active}"/>
</li>
</ul>
这是供引用的Role
类:
public class Role {
private String name;
private boolean active;
public Role(String name, boolean active) {
this.name = name;
this.active = active;
}
public String getName() {
return name;
}
public boolean isActive() {
return active;
}
}
关于java - Thymeleaf 复选框以及数据库中的对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538692/