我正在努力解决一些百万富翁的问题 - 我正在尝试创建用于编辑保存在mysql db中的现有用户的表单。我想要实现的是我的表单中的checboxes列表,我可以看到已检查的角色(根据DB的信息),并可选择通过选中/取消选中其他角色来更改它们。
查看:
<!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>
控制器方法:
@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;
答案 0 :(得分:0)
标签
<form:checkboxes items="${rolesList}" path="roles" />
用于JSP模板,而Thymeleaf有自己的基于HTML的标签系统(带有Thymeleaf独有的附加标签),默认情况下不使用JSP标签。
您想要实现的目标与下面的代码类似。您必须更改它以使其与您的Role
类匹配。我使用了一个名为String对象的简单类和一个与它的checked函数对应的布尔值。
<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;
}
}