如何处理同一 URI 上的无参数和参数化 REST 服务

How to handle parameter-less and parameterized REST service on same URI

我正在 Spring 引导环境中使用 REST 服务。我对 URI 和命名约定有疑问。

我(当前)在我的控制器实现中有以下三个映射...

@RequestMapping(method=RequestMethod.GET, value= "/v1/accounts")
public List<Account> getAllAccounts() {
    return accountService.getAllAccounts();
}

@RequestMapping(method=RequestMethod.GET, value="/v1/accounts/{accountId}")
public Account getAccount(@PathVariable int accountId) {
    return accountService.getAccount(accountId);
}

@RequestMapping(method=RequestMethod.GET, value="/v1/accounts/")
public Account getAccount(@RequestParam("shortName") String shortName) {
    return accountService.getAccount(shortName);
}

这些目前 "work",但我有一个关于 getAccount(String) 方法的 question/concern。如果我只是使用路径 "v1/accounts",编译器似乎无法将其与 getAllAccounts() 的 URI 区分开来。所以,我添加了尾随的“/”,请求现在看起来像...

/v1/accounts/?shortName=foo

不过,这两个请求似乎应该是...

/v1/accounts

/v1/accounts?shortName=foo

但是,如前所述,更改第三个请求映射以删除尾随的“/”会导致编译时错误。

关于 (a) 如何在不 运行 的情况下消除编译时错误的尾随 '/',或 (b) 合并尾随 '/' "just" 的可取性的任何输入公开两个 REST 服务(我担心 "what happens when the 3rd service is needed")?

在与我们的一位前端开发人员交谈后,他说最好只处理一种 return 类型(即 List vice List 和 Account),事情简化为...

@RequestMapping(method=RequestMethod.GET, value="/v1/accounts")
public List<Account> getAccount(@RequestParam("shortName") Optional<String> shortName) {
    return (shortName.isPresent()) ? accountService.getAccount(shortName.get())
                                   : accountService.getAccounts();
}

我看到一些关于使用 "Optional" 作为参数类型的担忧,但它似乎 (a) 清理了 REST 端点的 URI,并且 (b) 在控制器中并不可怕实施。

除非有人指出 "big, unanticipated nightmare" 与此方法相关,否则我想我会 运行 使用此