java - Spring Boot使用pathvariable从url获取id

标签 java spring spring-boot spring-mvc

我正在努力从 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";
    }

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

关于java - Spring Boot使用pathvariable从url获取id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59577705/

相关文章:

java - Spring DBCP 连接池 |配置重试次数

docker - 在 vagrant 和 docker 中调试 spring boot

java - 未知的生命周期阶段 "spring-boot"

java - OAuth2 WebSecurityConfigurerAdapter 规则的意义是什么,因为它没有比 ResourceServerConfigurerAdapter 更高的优先级

java - Java 类可以知道它的实例化器吗?

java - Java 中最好的可调整大小的循环字节缓冲区是什么?

java - Spring 作用域的问题

html - Spring SSEEmitter 中途完成

java - 在多维 ArrayList 中查找字符串

java - 通过 ID 检索用户对象