Reputation: 645
In the Get request method given below I want to check if more than 1 parameters are given in the request. It is only allowed to use one of the three possible parameters, when more than 1 is given I will throw an error.
@GetMapping()
public List<Offer> getOffers(@RequestParam(required = false) String title,
@RequestParam(required = false) String status,
@RequestParam(required = false) Double bidValue) {
if (title != null) {
return offerRepo.findByQuery("Offer_find_by_title", title);
}
if (status != null) {
if (EnumUtils.isValidEnum(Offer.Auctionstatus.class, status)) {
return offerRepo.findByQuery("Offer_find_by_status", Offer.Auctionstatus.valueOf(status));
}
else{
throw new
ResponseStatusException(HttpStatus.BAD_REQUEST, String.format("Status=%s is not a valid auction status ", status));
}
}
if (bidValue != null) {
return offerRepo.findByQuery("Offer_find_by_minBidValue", bidValue);
}
return offerRepo.findAll();}
How can I check if more than 1 RequestParam
is given in the request?
Upvotes: 0
Views: 1136
Reputation: 313
One of the possible solutions is to get request params as map and check the size of the map if it is bigger than 1 throw exception.
From @RequestParam
docs
If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.
public List<Offer> getOffers(@RequestParam Map<String, String> params) {
if(params.size() > 1) {
// throw exception
}
if (params.get("title") != null) {
return offerRepo.findByQuery("Offer_find_by_title", params.get("title"));
}
//...
}
Upvotes: 0
Reputation: 131496
How can I check if more than 1 RequestParam is given in the request?
Why not with a fast fail check by relying on the count of non null parameters ?
public List<Offer> getOffers(@RequestParam(required = false) String title,
@RequestParam(required = false) String status,
@RequestParam(required = false) Double bidValue) {
long countNonNull = Stream.of(title, status, bidValue).filter(Objects::nonNull).count();
if (countNonNull > 1){
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "expect not more than one parameter among : title, status, bidValue");
}
...
}
Upvotes: 1