[英]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.我有 Spring MVC 应用程序,我需要在控制器中获取有关当前请求的 RequestMappingInfo 或从 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
.在您的控制器中,将HttpServletRequest
添加到您的注释方法中,并在RequestMappingHandlerMapping
自动装配。 Then you can use getHandlerMapping()
to get information about the current RequestMappingInfo
.然后您可以使用getHandlerMapping()
获取有关当前RequestMappingInfo
。
For example, the following prints all pattern matched URLs:例如,以下打印所有模式匹配的 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)));
}
I have just read spring document and found this.我刚刚阅读了 spring 文档并找到了这个。
@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. @Nullable public RequestMappingInfo getMatchingCondition(HttpServletRequest 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.例如,返回的实例可能包含与当前请求匹配的 URL 模式子集,以最佳匹配模式排序。
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是的,您可以检索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.