How do I retrieve query parameters in Spring Boot?
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 ....
}
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.