How do you retrieve those parameters in the code ? The URL parameter is enclosed in braces in the relative path passed to @GetMapping annotation. The URL parameter is then retrieved using @PathVariable annotation which takes the variable indicated in enclosed braces as a parameter.
Query parameters are passed after the URL string by appending a question mark followed by the parameter name , then equal to (“=”) sign and then the parameter value. Multiple parameters are separated by “&” symbol.
Use @RequestParam
@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){
Item i = itemDao.findOne(itemid);
String itemName = i.getItemName();
String price = i.getPrice();
return i;
}
While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam
, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.
@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) {
if( itemid.isPresent()){
Item i = itemDao.findOne(itemid.get());
return i;
} else ....
}
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
In Spring boot: 2.1.6, you can use like below:
@GetMapping("/orders")
@ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
public List<OrderResponse> getOrders(
@RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
@RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
@RequestParam(value = "location_id", required = true) String location_id) {
// TODO...
return response;
@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With