簡體   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