我正在努力从 url 获取 id 来用作我的 read() 方法中的参数。 我阅读并看到了使用 @PathVariable 的示例,但我不明白为什么这不起作用。
这是我的 Controller 类。
@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";
}
关于java - Spring Boot使用pathvariable从url获取id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59577705/