2017-03-09 98 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 } 
    ... 
}); 
相關問題