【问题标题】:How can I use ID(arguments) to different GetMappings如何将 ID(参数)用于不同的 GetMappings
【发布时间】:2026-01-21 08:10:02
【问题描述】:

当我尝试 localhost:8080/api/employees 时,我得到一个列表(JSON 格式)。我还想通过 ID 获得一个员工。当我尝试 localhost:8080/api/123abc 时,我找不到具有该 ID 的员工。我的回答是:

白标错误页面 此应用程序没有 /error 的显式映射,因此您将其视为后备。

2020 年 7 月 28 日星期二 08:50:28 CEST 出现意外错误(type=Not 已找到,状态=404)。

我的代码在下面

@RestController
@RequestMapping(value = "/api", produces = MediaType.APPLICATION_JSON_VALUE)
public class TestApiController {
    @Autowired
    private EmployeePoller poller;

    @GetMapping(path = "/employees")
    public List<Employee> allEmployees() {
        return poller.getAllEmployees();
    }

    @GetMapping(path = "/{id}")
    public Employee singleEmployee(@PathVariable String id) {
        return poller.getEmployeeById(id);
    }

编辑:@PathVariable Long idpoller.getEmployeeById(id.toString()); 也不起作用。

【问题讨论】:

  • 从错误 404 我猜,没有 ID 为 123abc 的员工。我无法对此进行测试,因为我没有您的数据。
  • 当我尝试@GetMapping(path = "/{id}") public Employee singleEmployee(@PathVariable String id) { System.out.println(id); return poller.getEmployeeById(id); } 时,它也不会打印 id。但这项工作@GetMapping(path = "/123") public Employee singleEmployee() { return poller.getEmployeeById("123abc"); }
  • 你有没有调试看看它是否到达return poller.getEmployeeById(id);这一行?
  • 当你点击/employees端点时,你能在结果中找到id为“123abc”的用户吗?我的意思是它真的存在吗?

标签: java spring-boot api get-mapping


【解决方案1】:

404 - 未找到可能是:

  1. GET /api/123abc 未在您的控制器中声明为端点。
  2. 没有 id = 123abc 的员工。

要确认您的情况,请使用方法 OPTION 向 localhost:8080/api/123abc 发出新请求

如果响应是 404,则问题出在您的控制器中。如果响应为 200,则没有 id 为 123abc 的员工。

我还看到您对两个端点使用相同的路径。试试下面的代码(它验证“id”变量是否是员工)。

@GetMapping(path = "/{id}")
public Employee getEmployee(@PathVariable(name = "id") String id) {
    if ("employees".equals(id)) {
        return poller.getAllEmployees();
    } else {
        return poller.getEmployeeById(id);
    }
}

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
最近更新 更多