【问题标题】:getting null for @PathParam using springboot使用 Spring Boot 为 @PathParam 获取 null
【发布时间】:2019-03-30 06:09:23
【问题描述】:

我是 web 服务的新手,正在使用 spring-boot 来创建 web 服务,而在使用 http://localhost:8085/user/30?name=abc 发出请求时,我的 id 属性为空。`

 @GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
  public String  getUser(@PathParam("id") Long id,
                    @QueryParam("name") String name){
System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
return " Got id by path param : "+ id + " And Got name using Query Param " +name;
 }

编辑添加截图。

screenshot taken from Postman 提前致谢。

【问题讨论】:

  • 你想从请求中得到什么?用户名,或使用查询参数name? 指定的任何用户参数。
  • @Boris QueryParam 工作正常,但使用 PathParam

标签: rest web-services spring-boot


【解决方案1】:

您需要使用@PathVariable,因为您使用的是spring-rest 而不是@PathParam,即JAX-RS 注释

@GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String  getUser(@PathVariable("id") Long id,
                @QueryParam("name") String name){
    System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
    return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}

【讨论】:

  • 为什么@PathParam 不可能
  • 因为您使用的是 spring...@PathVariable 是 jax-rs @PathParam 的等效注释
  • 如果它解决了你的问题,别忘了接受我的回答
  • @Shiva 使用@QueryParam 真的对你有用吗?我不这么认为。
  • @valerioMC 谢谢
【解决方案2】:

我注意到您将Jax-RS 注释与Spring 注释混合在一起

试试这个,它会解决你的问题

@GetMapping(value="{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public String  getUser(@PathVariable("id") Long id,
        @RequestParam("name") String name){
    System.out.println(" Got id by path param : "+ id + " And Got name using Query Param " +name);
    return " Got id by path param : "+ id + " And Got name using Query Param " +name;
}

【讨论】:

  • @GetMappping 是正确的,实际上 rest-service 正在响应... @PathParam 是错误的,正如我已经说过的那样
  • 应该是把“/user”放在班级级别
  • 那是你的假设。 OP 没有他的班级代码。
  • @Shiva 我修正了我的答案。
  • @Shiva 很清楚,也因为你会有一个 404
【解决方案3】:

对于id 变量,您必须使用@PathVariable 注释,对于name 参数,请使用@RequestParam

这是一个完整的工作解决方案:

@RestController
@RequestMapping("/user")
public class UserController {

  @GetMapping("/{id}")
  public String getUser(@PathVariable Long id, @RequestParam String name) {
    System.out.println(" Got id by path param : " + id + " And Got name using Query Param " + name);
    return " Got id by path param : " + id + " And Got name using Query Param " + name;
  }

}

更多详情请见here

现在当你提出请求时

$ curl http://localhost:8085/user/30?name=abc

您会收到回复:

 Got id by path param : 30 And Got name using Query Param abc

【讨论】:

    猜你喜欢
    • 2017-05-30
    • 2017-06-07
    • 2020-01-10
    • 2019-07-26
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 2020-05-21
    • 2014-12-15
    相关资源
    最近更新 更多