繁体   English   中英

如何从 HttpServletRequest 中检索 RequestMappingInfo?

[英]How can I retrieve RequestMappingInfo from HttpServletRequest?

我有 Spring MVC 应用程序,我需要在控制器中获取有关当前请求的 RequestMappingInfo 或从 HttpServletRequest 转换它。 有什么办法可以做到吗?

@GetMapping
public void test(RequestMappingInfo requestMappingInfo,
                 Authentication auth) {
    service.verify(requestMappingInfo, auth);
}

在您的控制器中,将HttpServletRequest添加到您的注释方法中,并在RequestMappingHandlerMapping自动装配。 然后您可以使用getHandlerMapping()获取有关当前RequestMappingInfo

例如,以下打印所有模式匹配的 URL:

@Autowired
private RequestMappingHandlerMapping handlerMapping;

@GetMapping
public void test(RequestMappingInfo requestMappingInfo,
             Authentication auth,
             HttpServletRequest request) {

    handlerMapping.getHandlerMethods()
            .forEach((requestMappingInfo, handlerMethod)
                    -> System.out.println(requestMappingInfo.getPatternsCondition().getMatchingCondition(request)));

}

我刚刚阅读了 spring 文档并找到了这个。

@Nullable public RequestMappingInfo getMatchingCondition(HttpServletRequest request) 检查此请求映射信息中的所有条件是否与提供的请求匹配,并返回一个潜在的新请求映射信息,其条件适合当前请求。 例如,返回的实例可能包含与当前请求匹配的 URL 模式子集,以最佳匹配模式排序。

指定者:

getMatchingCondition in interface RequestCondition<RequestMappingInfo>

我没有试过这个代码,请你检查一下?

考试:

private 
@Autowired HttpServletRequest request;

@GetMapping
public void test(RequestMappingInfo requestMappingInfo, Authentication auth{
        assertEquals(requestMappingInfo, requestMappingInfo.getMatchingCondition(request));
}

是的,您可以检索requestMappingInfo ,请尝试以下代码

@Autowired
private RequestMappingHandlerMapping handlerMapping;

@GetMapping
public void test(Authentication auth,
             HttpServletRequest request) {

    RequestMappingInfo requestMappingInfo = handlerMapping
      .getHandlerMethods()
      .entrySet()
      .stream()
      .filter(entry -> entry.getKey().getMatchingCondition(request) != null)
      .findFirst()
      .map(entry -> entry.getKey())
      .orElse(null);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM