Daniel Perník
Daniel Perník

Reputation: 5872

Spring REST get url path for multiple mapped endpoint

I have REST endpoint with multiple paths as following:

@RequestMapping(method = RequestMethod.POST, path = {"/xxx/yyy", "/zzz"})
@ResponseBody
public Mono<EpcPain> paymentOrder(@RequestHeader(name = "Timeout", defaultValue = "10000") int timeout,
                                  @RequestHeader(name = "X-Request-Id", required = false) String xRequestId) {
...
}

How can I resolve if request path was xxx/yyy or zzz? I do not want to duplicate this endpoint nor pass some params. I am looking for some spring code magic.

Upvotes: 0

Views: 2272

Answers (2)

R.G
R.G

Reputation: 7131

org.springframework.web.context.request.RequestContextHolder may be used to get the path

import static org.springframework.web.servlet.HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE;
import static org.springframework.web.servlet.HandlerMapping.LOOKUP_PATH;
import static org.springframework.web.servlet.HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE;

and

   @RequestMapping(value = {"/getDetails","/getDetailsMore"}, method = RequestMethod.GET)
    public String getCustomerDetails(TestFormBean bean) {
        RequestAttributes reqAttributes = RequestContextHolder.currentRequestAttributes();
    System.out.println(reqAttributes.getAttribute(BEST_MATCHING_PATTERN_ATTRIBUTE, 0));
    System.out.println(reqAttributes.getAttribute(LOOKUP_PATH, 0));
    System.out.println(reqAttributes.getAttribute(PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, 0));

        return "test";
    }}

All three prints the path.

Here 0 - is request scope and 1 - is session scope.

Hope this helps.

Upvotes: 2

cassiomolin
cassiomolin

Reputation: 130977

You could add ServerHttpRequest as a method argument and then get the URI for the current request using getURI(). It should work for both Spring MVC and Spring WebFlux.

Have a look at the handler methods documentation for details.

Upvotes: 1

Related Questions