restful 资源关联关系API设计


比如公司与权限,公司下的员工与权限的关系


 /orgs/:orgId/privileges

/orgs/:orgId/employees/:employeeId/privileges

采用 spring mvc 放在 OrgController

不知道这样对不对?

restful spring-mvc java

流汁D豆沙包 10 years, 4 months ago

 @ReqeustMapping("/org")
class OrgController

@ResponseBody
@ReqeustMapping("/{orgId}/privileges")
public List<Privilege> privileges(@PathVariable String orgId)

@ReqeustMapping("/employee")
class EmployeeController

@ResponseBody
@ReqeustMapping("/{employeeId}/privileges")
public List<Privilege> privileges(@PathVariable String employeeId)


当题主同学问到 某公司下某个员工的权限 的时候,我就感觉上面这些都没什么必要了。

先把 enable-matrix-variables 设为true


 <mvc:annotation-driven enable-matrix-variables="true" />



不用那么多方法来提供privilege,只要一个方法:


 @RequestMapping(value = "/privileges/{orgId}", method = RequestMethod.GET)
@ResponseBody
public List<Privilege> privileges(
         @PathVariable String orgId
        , @MatrixVariable(required = false) String userId) {
    List<Privilege> privileges = new ArrayList<>();

    //something

    return privileges;
}

Url可以是:/privileges/8866
或者 /privileges/8866;userId=0001

炮姐D凝视 answered 10 years, 4 months ago

链有点长,如果 org 相关的都要放到这个 controller 中就是导致这个文件越来越复杂

个人感觉这样会更好一点


 // OrgController
/orgs/:orgId

// EmployeesController
/orgs/:orgId/employees 

// EmployeesController
/employees/:employeeId

// PrivilegesController
/employees/:employeeId/privileges

// PrivilegesController
/orgs/:orgId/privileges

hopecyb answered 10 years, 4 months ago

Your Answer