Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

How to check if multiple RequestParameters are given in Get Java spring boot

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?

question from:https://stackoverflow.com/questions/65646821/how-to-check-if-multiple-requestparameters-are-given-in-get-java-spring-boot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"));
        }
        //...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...