1

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 ?

PAA
  • 1
  • 46
  • 174
  • 282

2 Answers2

2

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.

James
  • 11,654
  • 6
  • 52
  • 81
  • This is not working for me. Best matching patterns gives null to me – PAA Mar 04 '20 at 18:57
  • @PAA: Maybe your filter is executed before the handler mapping is done and this attribute is set? Could you use a ControllerAdvice instead of a filter? – James Mar 05 '20 at 16:12
  • For future readers who stumble upon this answer, `((HttpServletRequest)req).getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE))` works for me. But it must be used after `chain.doFilter()` when used in a filter. – red Feb 05 '22 at 09:23
0

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;
PAA
  • 1
  • 46
  • 174
  • 282