[英]I am using the Interceptor in springboot , but there I am getting the error as
[英]I getting an error while i am trying to update an user and not able to show my users roles using SpringBoot
登录后我想做什么,在用户页面中,我试图向所有用户显示他们的角色,当我点击其中一个的编辑时,我会进入 edit_user 页面,我将允许我编辑用户,但我得到这样做时出错,在 usersPage 中我看不到用户的角色。
用户实体:
@Entity
@Table(name = "users" ,uniqueConstraints = @UniqueConstraint(columnNames = "userName"))
public class Users {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userName;
private String password;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(
name = "users_roles",
joinColumns = @JoinColumn(
name = "user_id",referencedColumnName ="id"),
inverseJoinColumns = @JoinColumn(
name ="role_id" ,referencedColumnName ="id"
)
)
private Collection<Roles> roles;
public Users(String userName, String password, Collection<Roles> roles) {
this.userName = userName;
this.password = password;
this.roles = roles;
}
public Users()
{
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Roles> getRoles() {
return roles;
}
用户注册Dto
public class UserRegistrationDto {
private String userName;
private String password;
private Collection<Roles> role;
public UserRegistrationDto(String userName, String password, Collection<Roles> role) {
this.userName = userName;
this.password = password;
this.role = role;
}
public UserRegistrationDto()
{
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Roles> getRole() {
return role;
}
public void setRole(Collection<Roles> role) {
this.role = role;
}
}
用户控制器
在这个控制器层它负责获取、删除、编辑用户
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private RoleRepository roleRepository;
public UserController(UserService userService, RoleRepository roleRepository) {
this.userService = userService;
this.roleRepository = roleRepository;
}
@ModelAttribute("roles")
public List<Roles> initializeRoles(){
List<Roles> roles = roleRepository.findAll();
return roles ;
}
@GetMapping("/users/AllUsers")
public String getAllUsers(Model model)
{
model.addAttribute("user",userService.getAlluser());
return "Users/users";
}
@GetMapping("/user/edit/{id}")
public String editUserForm(@PathVariable long id, Model model)
{
model.addAttribute("user",userService.getUserById(id));
return "Users/edit_user";
}
@RequestMapping(value = "/user/update/{id}",method = RequestMethod.POST)
public String updateUser(@PathVariable Long id, @ModelAttribute("user") UserRegistrationDto registrationDto)
{
Users userExisting = userService.getUserById(id);
userExisting.setId(id);
userExisting.setUserName(registrationDto.getUserName());
userExisting.setRoles(registrationDto.getRole());
userService.updateUser(userExisting);
return "redirect:/users/AllUsers";
}
@GetMapping("/user/delete/{id}")
public String deleteUser(@PathVariable long id)
{
userService.deleteUser(id);
return "redirect:/users/AllUsers";
}
}
用户服务
//save a user from the userRegistration form that been shown in the class model
public Users save(UserRegistrationDto registrationDto)
{
//Users user = new Users(registrationDto.getUserName(),passwordEncoder.encode(registrationDto.getPassword()),Arrays.asList(new Roles(registrationDto.setRole(registrationDto.getRole()))));;//Arrays.asList(new Roles("ROLE_USER"))
Users usersEntity = new Users();
usersEntity.setUserName(registrationDto.getUserName());
usersEntity.setRoles(registrationDto.getRole());
usersEntity.setPassword(passwordEncoder.encode(registrationDto.getPassword()));
return userRepository.save(usersEntity);
}
@Override
public Users getUserById(Long id) {
return userRepository.findById(id).get();
}
//we converting roles to authorities
private Collection <? extends GrantedAuthority> mapRolesToAuthorities(Collection<Roles> roles) {
return roles.stream()
.map(role -> new SimpleGrantedAuthority(role.getName()))
.collect(Collectors.toList());
}
edit_user.html
<form th:action="@{/user/update/{id}}" method="post" th:object="${user}">
<div class="form-group">
<label class="control-label" for="userName"> Username </label>
<input id="userName" class="form-control" th:field="*{userName}" required autofocus="autofocus" />
</div>
<div class="col-1.5">
<label th:for="roles"> User Type: </label>
<select class="form-control form-control-sm" id="roles" name="roles">
<option value="">Select User Type</option>
<option th:each = "role: ${roles}"
th:value="${role.id}"
th:text="${role.name}"
>
</option>
</select>
</div>
<div class="form-group">
<label class="control-label" for="password"> Password </label> <input
id="password" class="form-control" th:field="*{password}" required autofocus="autofocus" type="password" />
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</form>
users.html 我将在其中显示所有用户
<section class="table_content">
<!--main-container-part-->
<div id="content">
<!--End-breadcrumbs-->
<!--Action boxes-->
<div class ="container">
<div class = "row">
<h1> All Users </h1>
</div>
<br>
<br>
<table class = "table table-striped table-bordered">
<thead class = "table-dark">
<tr>
<th> Name </th>
<th> Roles </th>
<th> Edit </th>
<th> Delete </th>
</tr>
</thead>
<tbody>
<tr th:each = "user: ${user}"> <!-- this attribute to list up products -->
<td th:text="${user.userName}" ></td>
<td th:text="${user.roles}"></td>
<td> <center> <a th:href="@{/user/edit/{id}(id=${user.id})}" style="color: green"> Edit </a> </center> </td>
<td> <center> <a th:href="@{/user/delete/{id}(id=${user.id}) }" style="color: red"> Delete </a> </center> </td>
</tr>
</tbody>
</table>
</div>
</div>
您犯的第一个错误是在 edit_user.html 中,正如您提供的堆栈跟踪所说,端点 /user/update/{id} 无法将 '{id}' 转换为 long。 那是因为您传递的 id 不是用户 id,而是字符串 '{id}' 本身。
在 edit_user.html 中更改:
<form th:action="@{/user/update/{id}}" method="post" th:object="${user}">
到
<form th:action="@{/user/update/{id}(id=${user.id})}" method="post" th:object="${user}">
如果这仍然不起作用,我建议也将 userID 作为模型中的属性传递。
对于第二个问题,由于 users.html 中的这一行,您无法可视化用户角色:
<td th:text="${user.roles}"></td>
由于 User.roles 是一个集合,它不能“一次”呈现,您必须使用 edit_user 中使用的相同语法,因此:
<td>
<p th:each="role: ${user.roles}" th:text="${role.name}"></p>
</td>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.