【发布时间】:2017-07-30 15:43:04
【问题描述】:
我必须在我的应用程序中为用户添加一个或多个角色。目前我使用这种方法一次向用户添加一个角色:
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 在我的 update 方法中将角色添加到用户?
【问题讨论】:
标签: spring rest spring-boot restful-architecture spring-rest