【问题标题】:add role to user RESTful [Spring-Rest]将角色添加到用户 RESTful [Spring-Rest]
【发布时间】: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;
}

此方法工作正常,但问题是:

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

我的问题是:

如何在 REST 的概念中为用户添加一个或多个角色? 我什至应该有一种特定的方法来为用户添加角色吗?还是我应该通过 PUT 在我的 update 方法中将角色添加到用户?

【问题讨论】:

    标签: spring rest spring-boot restful-architecture spring-rest


    【解决方案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 还是 PUT? ..我都不会说。 PATCH 是正确的,因为您没有创建新的对象/实体,也没有更新整个对象。相反,您只更新对象的一个​​字段(参见此处:https://spring.io/understanding/REST)。您的 PATCH 调用也是幂等的,这意味着重复执行相同的调用总是返回相同的结果。

    如果您想在请求中为 roleIds 使用参数(更适合 PATCH 的“仅更新 URI 上实体的指定字段。”要求strong>) 它应该是这样的:

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

    您必须尝试使用​​List&lt;Long&gt;

    相应的客户端调用(在 jQuery 中)如下所示:

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

    【讨论】:

      猜你喜欢
      • 2022-07-25
      • 1970-01-01
      • 1970-01-01
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多