2017-03-09 53 views
0

我必须在我的应用程序中添加一个或多个用户角色。目前,我每次一个角色添加到用户使用这种方法:将角色添加到用户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; 
} 

此方法效果很好,但问题是:

  1. 的方法只能一次向一个用户添加一个角色
  2. 该方法不是RESTful

我的问题是:

如何添加一个或多个角色给用户的概念REST? 我应该甚至有一个特定的方法来为用户添加角色?或者我应该将角色添加到我的更新中的用户 - 方法PUT

回答

1

,我发现这是一个有效的建议:

@RequestMapping(value="/test/{firstNameIds}", method=RequestMethod.GET) 
@ResponseBody 
public String test(@PathVariable List<Integer> firstNameIds) { 
    //Example: pring your params 
    for(Integer param : firstNameIds) { 
     System.out.println("id: " + param); 
    } 
    return "Dummy"; 
} 

什么对应于这样一个URL:GET http://localhost:8080/public/test/1,2,3,4

IntegerLong也应努力Insteaf。

POST or PUT?他们都不会说。 修补程序是正确的,因为您没有创建新的对象/实体,也没有更新整个对象。相反,您只更新对象的一个​​字段(请参阅:https://spring.io/understanding/REST)。您的PATCH调用也是幂等的,意味着重复执行的相同调用总是返回相同的结果。

如果你要使用roleIds参数在你的请求(会更适合于“更新在URI实体的唯一指定字段。” PATCH的要求)就应该是这样的:

@RequestMapping(value="users/{id}", method = RequestMethod.PATCH) 
public void action(@PathVariable Long id, @RequestParam(value = "param[]") String[] roleIds) { 
    ... 
} 

您必须试用List<Long>

相应的客户端调用(jQuery的)看起来像:

$.ajax({ 
    type: "PATCH", 
    data: { param:roleIds } 
    ... 
}); 
相关问题