Reputation: 1575
Am developing an application using spring boot. In Resource am using path variable(**@PathVariable**
annotation) and Request Param(**@RequestParam("name")**
annotation). My code fetching the request param value but not the path variable value,I am getting the path variable value as null. Please any one suggest me to solve this issue.
@RequestMapping(value = "/api/user/{id}", method = RequestMethod.GET)
public void get(@RequestParam("name") String name, @PathVariable Integer id); {
System.out.println("name="+name);
System.out.println("id="+id)
}
URL:
http://localhost:8080/api/user/2?name=neeru
OUTPUT:
name=neeru
id=null
i also tried
**@RequestMapping(value = "/api/user/id={id}", method = RequestMethod.GET)**
URL:
http://localhost:8080/api/user/id=2?name=neeru
but getting same id value=null
i have added one more method -only has @PathVariable
@RequestMapping(path="/api/user/name/{name}", method = RequestMethod.GET)
void get( @PathVariable("value=name") String name){
System.out.println("name="+name)
}
but result is same path variable value name=null
Upvotes: 2
Views: 16266
Reputation: 184
Change your endpoint like this
http://localhost:8080/api/user/2/users?name=neeru
`
@RequestMapping(value = "api/user/{id}/users", method = RequestMethod.GET)
public void get(@RequestParam("name") String name, @PathVariable("id") Integer id); {
System.out.println("name="+name);
System.out.println("id="+id)
}
`
Output:
name = neeru
id = 2
Upvotes: 6
Reputation: 36103
@PathVariable is used for extracting variables in the path like MystyxMac suggested. If you want to extract query parameters then you must use @RequestParam
But your example is a mix of path and query parameter.
You cannot use = in an URL because this is a reserved character: https://www.w3.org/Addressing/URL/url-spec.txt
So either use
/api/user/{id} with @PathVariable
or
/api/user?id={id} with @RequestParam
Upvotes: 5