Spring - 在拦截器/过滤器中获取给定请求的方法 [英] Spring - get Method for a given request in Interceptor/Filter
问题描述
我的 @Controller
类中的各种 @RequestMapping
方法都有我想在运行时分析的自定义注释.
Various @RequestMapping
methods inside my @Controller
classes have custom annotations that I want to analyze at runtime.
例如:
@Controller
@RequestMapping("/bla")
@RequireCommunityLevel("...")
@AnotherCustomAnnotation(value = "...")
public class FakeController {
// ...
@RequireScore(level = Score.Platinum, score = 8500)
@RequestMapping("/blabla")
@AnotherCustomAnnotation(value = "...")
public DTOResponse<MySpecialModel> getMySpecialModels() {
// ...
}
}
当我在自定义 Interceptor
和 Filter
类中收到请求时,我想分析该请求将调用哪个 Method
.
When I receive a request in my custom Interceptor
and Filter
classes, I want to analyze which Method
the request is going to call.
我过去曾使用基于 Javax Servlet
和 Jetty
的自定义框架,并且经常实现某种方法注册询问.
I have worked in the past with custom frameworks based on Javax Servlet
and Jetty
and often implemented some kind of method-registry one could interrogate.
例如:
public class CustomFilter extends Filter {
@Inject
private MyMethodRegistry registry;
@Override
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// get the request path
final String path = getPath(request);
final Method m = this.registry.getMethodForPath(path);
// that's what I mean to do
if (m.getAnnotation(RequireScore.class) != null) { ... }
if (m.getDeclaringClass().getAnnotation(AnotherCustomAnnotation.class != null) { ... }
chain.doFilter(request, response);
}
}
我正在 Spring
中寻找类似的方法,可能是一个内置实用程序,用于在运行时分析我的 @RequestMapping<上的
Annotation
/代码> 方法.所有这些都应该发生在我的拦截器/过滤器中.
I'm looking for a similar way in Spring
, possibly a built-in utility to analyze at runtime the Annotation
's on my @RequestMapping
methods. All of this should happen within my Interceptor/Filter.
推荐答案
正如@M.Deinum 在评论中所建议的,您可以在 Interceptor
中获取 Handler
作为参数.
As @M.Deinum advised in the comments you can get the Handler
as parameter in your Interceptor
.
我还发现了 本教程准确地解释了我所需要的.
I have also found this tutorial that explains exactly what I needed.
在HandlerInterceptor::preHandle
final HandlerMethod handlerMethod = (HandlerMethod) handler; // the last parameter
final Method method = handlerMethod.getMethod();
// check for annotations
这篇关于Spring - 在拦截器/过滤器中获取给定请求的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!