我必須在我的應用程序中添加一個或多個用戶角色。目前,我每次一個角色添加到用戶使用這種方法:將角色添加到用戶RESTful [Spring-Rest]
UserController.java
@RequestMapping(value = "users/{id}/{roleId}", method = RequestMethod.POST)
public User assignRole(@PathVariable Long id, @PathVariable Long roleId) throws NotFoundException {
log.info("Invoked method: assignRole with User-ID: " + id + " and Role-ID: " + roleId);
User existingUser = userRepository.findOne(id);
if(existingUser == null){
log.error("Unexpected error, User with ID " + id + " not found");
throw new NotFoundException("User with ID " + id + " not found");
}
Role existingRole = roleRepository.findOne(roleId);
if(existingRole == null) {
log.error("Unexpected error, Role with ID " + id + " not found");
throw new NotFoundException("Role with ID " + id + " not found");
}
Set<Role> roles = existingUser.getRoles();
roles.add(existingRole);
existingUser.setRoles(roles);
userRepository.saveAndFlush(existingUser);
log.info("User assigned. Sending request back. ID of user is " + id + existingUser.getRoles());
return existingUser;
}
此方法效果很好,但問題是:
- 的方法只能一次向一個用戶添加一個角色
- 該方法不是RESTful
我的問題是:
如何添加一個或多個角色給用戶的概念REST? 我應該甚至有一個特定的方法來爲用戶添加角色?或者我應該將角色添加到我的更新中的用戶 - 方法PUT?