使用 springboot 获取 null 表示@PathParam



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

@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;
}

编辑以添加屏幕截图。

截图取自邮递员 提前谢谢。

您需要使用@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;
}

我注意到您将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;
}

对于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;
}
}

有关更多详细信息,请参阅此处。

现在,当您提出请求时

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

您会收到回复:

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

相关内容

  • 没有找到相关文章

最新更新