首页 > 解决方案 > 在spring拦截器中获取请求映射对象,获取实际的url字符串模式

问题描述

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

Like if I have a GET URL as "/Test/x/{number}" 
I want to get "/Test/x/{number}" not "/Test/x/1"

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

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

标签: javaspringspring-mvcspring-boot

解决方案


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

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;
    }
}

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

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

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


推荐阅读