【问题标题】:How to get the current Request Mapping URL configured at Controller layer when request is executed?执行请求时如何获取在Controller层配置的当前请求映射URL?
【发布时间】:2020-06-12 06:25:24
【问题描述】:

我浏览了很多链接,例如 How to show all controllers and mappings in a viewHow to configure a default @RestController URI prefix for all controllers? 等等。

我想在过滤器拦截器中获取请求映射 URL

例如:我在 REST 控制器方法中配置的这个 URL,我们自然会通过 /employees/employee-names/John 来获取 Employee John。

/employees/employee-names/{employee_name}

现在,当有人点击 /employees/employee-names/John 时,如果 REST 控制器 /employees/employee-names/{employee_name},我想获取实际映射 url 的值,

任何指针如何得到它?

【问题讨论】:

标签: spring-boot spring-rest


【解决方案1】:

我能够使用以下代码解决此问题。 AntPathMatcher 是识别传入请求和您在属性文件中配置的 URL 是否完全匹配的完美方法。这个解决方案对我很有用。

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;

【讨论】:

    【解决方案2】:

    Spring MVC 设置属性HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE,您可以使用它来获取用于匹配传入请求的模式:

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

    在您的情况下,这将返回 /employees/employee-names/{employee_name}

    【讨论】:

    • 这对我不起作用。最佳匹配模式给我 null
    • @PAA: 也许你的过滤器是在处理程序映射完成并且设置了这个属性之前执行的?你能用 ControllerAdvice 代替过滤器吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-11
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    相关资源
    最近更新 更多