英文:
How can I use ID(arguments) to different GetMappings
问题
当我尝试访问 localhost:8080/api/employees 时,我会得到一个员工列表(以JSON格式)。我还希望能够通过ID获取单个员工的信息。当我尝试访问 localhost:8080/api/123abc 时,无法找到具有该ID的员工。我的响应是:
> Whitelabel Error Page
> 此应用程序未显式映射 /error,因此您看到了这个回退页面。
>
> Tue Jul 28 08:50:28 CEST 2020 发生了意外错误(类型=Not Found,状态=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 id` 和 `poller.getEmployeeById(id.toString());` 也无效。
}
英文:
When I try localhost:8080/api/employees I get a list (JSON-format). I would also like to get a single employee by ID. When I try localhost:8080/api/123abc I cannot find the employee with that ID. My response is:
> Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
>
> Tue Jul 28 08:50:28 CEST 2020 There was an unexpected error (type=Not
> Found, status=404).
My code is below here
@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);
}
edit: @PathVariable Long id
and poller.getEmployeeById(id.toString());
doesn't work either.
答案1
得分: 1
404 - 未找到 可能是:
- GET /api/123abc 在您的控制器中未声明为端点。
- 没有 id = 123abc 的员工。
要确认您的情况,请使用方法 OPTION 对 localhost:8080/api/123abc 进行新的请求。
如果响应是 404,则问题在于您的控制器。如果响应是 200,则没有 id 为 123abc 的员工。
此外,我看到您在两个端点上都使用了相同的路径。请尝试以下代码(它验证“id”变量是否为 employees)。
@GetMapping(path = "/{id}")
public Employee getEmployee(@PathVariable(name = "id") String id) {
if ("employees".equals(id)) {
return poller.getAllEmployees();
} else {
return poller.getEmployeeById(id);
}
}
英文:
The 404 - Not found could be:
- GET /api/123abc isn't declared as endpoint in your controller.
- There isn't employee with id = 123abc.
To confirm what's your case, do a new request with method OPTION to localhost:8080/api/123abc
If the response is 404, the issue is in your controller. If response is 200, then there isn't employee with id 123abc.
Also I see you are using the same path for both endpoints. Try the following code (It validate if "id" variable is employees).
@GetMapping(path = "/{id}")
public Employee getEmployee(@PathVariable(name = "id") String id) {
if ("employees".equals(id)) {
return poller.getAllEmployees();
} else {
return poller.getEmployeeById(id);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论