java - Spring Boot 使用 pathvariable 从 url 获取 id
问题描述
我正在努力从 url 获得一个 id 以用作我的 read() 方法中的参数。我阅读并看到了使用 @PathVariable 的示例,但我不明白为什么这不起作用。
这是我的控制器类。
@GetMapping("details/{id}")
public String read(@PathVariable int employeeId, Model model)
{
model.addAttribute("students_data", studentsRepo.read(employeeId));
//the line underneath will work using as an example the int 2 in the parameter. But I want the int coming from the url.
//model.addAttribute("students_data", studentsRepo.read(2));
return "details";
}
我在详细信息页面上收到错误:
Fri Jan 03 12:13:44 CET 2020
There was an unexpected error (type=Not Found, status=404).
No message available
url 的外观示例如下:
http://localhost:8080/details?id=2
解决方案
您共享的 URLhttp://localhost:8080/details?id=2
包含 @RequestParam 而不是 @PathVariable
如果你想使用 @RequestParam 那么你的 API 签名应该是
@GetMapping("details/")
public String read(@RequestParam("id") int employeeId, Model model)
{
"details";
}
如果你想使用 @PathVariable 那么你的 API 应该是
@GetMapping("details/{id}")
public String read(@PathVariable("id") int employeeId, Model model)
{
"details";
}
推荐阅读
- docker - Flannel 网络在 Kubernetes 安装期间出现故障,请建议如何解决此问题
- laravel - Laravel 非常短期的缓存?
- swift - 出现分段错误:使用 FileManager.default.currentDirectoryPath 时使用 Swift 5.2 时出现 11
- loopbackjs - Loopback 中的领域是什么?
- animation - 视频到 webp 转换器软件
- pytorch - 对象检测模型 (PyTorch) 到 ONNX:ONNX 推理的空输出
- c++ - C++,在 C++ 中管理文件的问题
- html - 下拉内容后面的元素显示在前面/带有下拉内容
- django - Django 自定义中间件 request.user 总是 AnonymousUser
- apache-zookeeper - Zookeeper 3.6.0 TCP 要求改变了吗?