2

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

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

2020 年 7 月 28 日星期二 08:50:28 CEST 出现意外错误(类型=未找到,状态=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());不起作用。

4

1 回答 1

1

404 - Not found 可能是:

  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);
    }
}
于 2020-07-28T09:02:05.600 回答