使用springboot为@PathParam获取null

时间:2018-10-25 15:03:39

标签: rest web-services spring-boot

我是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 预先感谢。

3 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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