首页 > 解决方案 > 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

标签: javaspringspring-bootspring-mvc

解决方案


您共享的 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";
    }

请检查两者之间的区别 https://javarevisited.blogspot.com/2017/10/differences-between-requestparam-and-pathvariable-annotations-spring-mvc.html


推荐阅读