在 spring 拦截器中获取请求映射对象,以获取实际的 url 字符串模式

Aad*_*dam 6 java spring spring-mvc spring-boot

可能很难解释为什么,但我有这种情况,我需要获取当前请求的 url 的请求 url 映射字符串。

Like if I have a GET URL as "/Test/x/{number}" 
I want to get "/Test/x/{number}" not "/Test/x/1"
Run Code Online (Sandbox Code Playgroud)

我可以在拦截器中获取实际声明的 url 字符串吗?

如果这是可能的,我怎么能做到这一点

Dar*_*the 7

您可以实现 aHanderInterceptor来拦截、预先或发布、请求和内省被调用的方法。

public class LoggingMethodInterceptor implements HandlerInterceptor {
    Logger log = LoggerFactory.getLogger(LoggingMethodInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HandlerMethod method = (HandlerMethod) handler;

        GetMapping mapping = method.getMethodAnnotation(GetMapping.class);

        log.info("URL is {}", Arrays.toString(mapping.value()));

        return true;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将输出, URL is [/hello/{placeholder}]

完整的例子可以在这里找到,https://github.com/Flaw101/spring-method-interceptor

您可以添加更多逻辑以仅内省某些方法、某些类型的请求等。