[英]Spring boot using pathvariable to get hold of an id from url
我正在努力从 url 中获取一个 id 以用作我的 read() 方法中的参数。 我阅读并看到了使用 @PathVariable 的示例的 dusin,但我不明白为什么这不起作用。
这是我的控制器类。
@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
网址的外观示例如下:
http://localhost:8080/details?id=2
您共享的 URL http://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";
}
使用@PathVariable("id") or @PathVariable int id
而不是employeeId
public String read(@PathVariable("id") int employeeId, Model model)
您正在使用 PathVariable。 因此 URL 将是:
http://localhost:8080/details/2
如果你想要你的 URL http://localhost:8080/details?id=2那么你必须使用 QueryParameter
@GetMapping("details")
public String read(@RequestParameter int id, Model model)
添加路径模式中变量的名称。
@PathVariable("id")
添加调用它
http://localhost:8080/details/2
如果您使用不同的变量名称,则必须将id
映射到PathVariable
,
@GetMapping("details/{id}")
public String read(@PathVariable("id") int employeeId, Model model)
您可以使用isPresent()
方法检查 url 如果“id”出现在 url 上
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.