简体   繁体   中英

How can I retrieve RequestMappingInfo from HttpServletRequest?

I have Spring MVC application and I need to get RequestMappingInfo in controller about current request or cast it from HttpServletRequest. Is there any way I can do it?

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

In your controller, add HttpServletRequest to your annotated method and autowire in a RequestMappingHandlerMapping . Then you can use getHandlerMapping() to get information about the current RequestMappingInfo .

For example, the following prints all pattern matched URLs:

@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)));

}

I have just read spring document and found this.

@Nullable public RequestMappingInfo getMatchingCondition(HttpServletRequest request) Checks if all conditions in this request mapping info match the provided request and returns a potentially new request mapping info with conditions tailored to the current request. For example the returned instance may contain the subset of URL patterns that match to the current request, sorted with best matching patterns on top.

Specified by:

getMatchingCondition in interface RequestCondition<RequestMappingInfo>

I didn't try this code , please can you check?

Exam:

private 
@Autowired HttpServletRequest request;

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

yes, You can retrieve the requestMappingInfo , try below code

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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