J
J
Jake Taylor2021-10-13 13:53:38
Java
Jake Taylor, 2021-10-13 13:53:38

Why doesn't a GET request hit a @GetMapping annotated method with parameters in Spring?

There is a method in the controller that handles the GET request. This method is annotated

@GetMapping(params = {ParameterName.SORT_BY, ParameterName.SORT_TYPE})
. This method in the arguments with the help of an annotation @RequestParambinds the argument that came from the GET request to a Java variable of the String type. It looks like this:

@GetMapping(params = {ParameterName.SORT_BY, ParameterName.SORT_TYPE})
    public List<GiftCertificate> findAllAndSort(@RequestParam(value = ParameterName.SORT_BY) String sortBy,
                                                @RequestParam(value = ParameterName.SORT_TYPE, required = false) String sortType) {
        log.info("Sorting: {}, {}", sortBy, sortType);
        return service.findAllAndSort(sortType, sortBy);
    }


The sortType argument has required = false , which means that this argument does not have to be present:
@RequestParam(value = ParameterName.SORT_TYPE, required = false) String sortType).


Then the question is why when requesting the view:
-
http://localhost:8080/gift-certificates?sort_by=name&sort_type=DESC

the request falls into this method.
-
http://localhost:8080/gift-certificates?sort_by=name

not included in this method.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BorLaze, 2021-10-13
@n199a

Because params in @___Mappingis designed to unambiguously bind a request to a method.
I.e,

@GetMapping(params = {ParameterName.SORT_BY, ParameterName.SORT_TYPE})
will be called ONLY if both parameters are present in the url. Whether indicated required = falseor not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question