我是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;
}
已编辑以添加屏幕截图。
答案 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