Home > database >  Differnece between @path variable vs @queryParan
Differnece between @path variable vs @queryParan

Time:06-25

When we can use @path variable vs when we can use @queryParameter

CodePudding user response:

For instance, let's say you want to have an url for fetching a specific order with id: OR-21345678

The "template" url you probably will have would look like this: https://example.org/order/{id}, therefore the url for the order OR-21345678 would be: https://example.org/order/OR-21345678. As we can see we have a variable which is located inside the path, that's why it is called @PathVariable and you can use it like this:

@RequestMapping(value = "/orders/{id}", method = RequestMethod.GET)
@ResponseBody
public String getOrder(@PathVariable final String id) {
  return "Order ID: "   id;
}

Following the same example, let's say you would like to add some filters like a specific state. You can do it using a query parameter which could be: https://example.org/order/OR-21345678?state=PENDING. In that case you will use a @QueryParam:

@RequestMapping(value = "/orders/{id}", method = RequestMethod.GET)
@ResponseBody
public String getOrder(@PathVariable final String id, @QueryParam("state") String state) {
  return "Order ID: "   id   "\nState: "   state;
}
  • Related