【问题标题】:Spring - get Method for a given request in Interceptor/FilterSpring - 在拦截器/过滤器中获取给定请求的方法
【发布时间】:2018-01-05 12:04:45
【问题描述】:

@Controller 类中的各种@RequestMapping 方法具有我想在运行时分析的自定义注释。

例如:

@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。

我过去曾使用基于Javax Servlet 和Jetty 的自定义框架,并且经常实现某种可以查询的方法注册表。

例如:

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。所有这些都应该发生在我的拦截器/过滤器中。

【问题讨论】:

  • 如果您使用HandlerInterceptor,您已经拥有所需的处理程序。
  • @M.Deinum 好吧,你的意思是 handler 对象在 preHandle 中作为参数传递?
  • 那个是的。

标签: java spring spring-mvc reflection annotations


【解决方案1】:

正如 @M.Deinum 在 cmets 中建议的那样,您可以在 Interceptor 中获取 Handler 作为参数。

我还找到了this tutorial,它准确地解释了我需要什么。

在HandlerInterceptor::preHandle

final HandlerMethod handlerMethod = (HandlerMethod) handler; // the last parameter
final Method method = handlerMethod.getMethod();

// check for annotations

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2012-02-15
    • 2019-10-04
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多