PAA
PAA

Reputation: 12015

How to get the current Request Mapping URL configured at Controller layer when request is executed?

I went through so many links like How to show all controllers and mappings in a view and How to configure a default @RestController URI prefix for all controllers? and so on.

I want to get the Request Mapping URL at Filter interceptor

Ex: This URL I configured at REST controller method, and naturally we will pass /employees/employee-names/John to get the Employee John.

/employees/employee-names/{employee_name}

Now, when somebody hit /employees/employee-names/John I want to get the value of actual mapping url if REST controller /employees/employee-names/{employee_name},

Any pointers how to get that ?

Upvotes: 2

Views: 1755

Answers (2)

James
James

Reputation: 12192

Spring MVC sets the attribute HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE, which you can use to get the pattern that was used to match the incoming request:

String matchingPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)

That would return /employees/employee-names/{employee_name} in your case.

Upvotes: 4

PAA
PAA

Reputation: 12015

I was able to solve this issue using below code. AntPathMatcher is the perfect way to identify if the incoming request and URL you configured in the property file matches exactly. This solution works greatly for me.

AntPathMatcher springMatcher = new AntPathMatcher();
Optional<String> antMatch = props.getMapping().stream()
     .filter(//Perform Some Filter as per need)
    .map(Mapping::getVersion)
    .findFirst();
return antMatch.isPresent() ? antMatch.get() : null;

Upvotes: 0

Related Questions