java - Spring - 获取拦截器/过滤器中给定请求的方法

标签 java spring spring-mvc reflection annotations

我的 @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() {
        // ...
    }

}

当我在我的自定义 InterceptorFilter 类中收到请求时,我想分析该请求将调用哪个 Method

我过去使用过基于 Javax ServletJetty 的自定义框架,并且经常实现某种方法注册审讯。

例如:

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

最佳答案

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

我还找到了this tutorial这正是我所需要的。

HandlerInterceptor::preHandle

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

// check for annotations

关于java - Spring - 获取拦截器/过滤器中给定请求的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48113283/

相关文章:

java - 如何通过 AJAX 在 Spring MVC 中呈现平铺 View ?

java - 这个引用转义单线程程序

eclipse - 类未找到 : org. springframework.web.servlet.DispatcherServlet

java 。运行和处理位图上每个像素的最快方法是什么?

java - 在 Azure 应用服务上部署 Spring Boot jar

java - 在自定义启动器中访问 spring 应用程序名称

java - 在 Spring Boot 2.1.1.RELEASE 中的 RestTemplate 中添加 Http header

spring - 使用 Spring MVC 和 Hibernate 4.2.0.Final 的 Multi-Tenancy Web 应用程序

java - 针对 Spring Security 的应用程序身份验证

Java:从大文件中获取随机行