【问题标题】:Spring Boot/MVC filters by annotationSpring Boot/MVC 通过注解过滤
【发布时间】:2015-03-01 05:46:10
【问题描述】:

我正在将 Web 应用程序转换为使用 spring-boot。 该应用程序当前使用我想转换为使用 spring-rest/mvc 的 resteasy。

到目前为止,它真的很简单(主要是替换注释)。 我遇到问题的一个地方与过滤器(HTTP 过滤器)有关。

目前,该应用程序有一个在一些端点中使用的过滤器。 注释用于指定过滤器应用于哪些休息点。注解基于@NameBinding

这可以用 Spring 来完成吗(即创建一个注解,并为我希望应用过滤器的每个 rest 端点方法添加注解)?

【问题讨论】:

    标签: spring-mvc spring-boot


    【解决方案1】:

    您可以定义一个过滤器类来扩展 OncePerRequestFilter 并覆盖 shouldNotFilter() 方法。您将 @Autowire RequestMappingHandlerMapping 获取与传入请求关联的处理程序。

    然后您可以简单地检查该处理程序方法是否包含注释。

    @Autowired
    private RequestMappingHandlerMapping reqMap;
    
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        HandlerMethod method = (HandlerMethod) reqMap.getHandler(request).getHandler();
        return !method.getMethod().isAnnotationPresent(SomeAnnotation.class);
    }
    
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
         // filtering logic
    }
    

    【讨论】:

      【解决方案2】:

      如果你正在使用 spring-boot,你可以使用 FilterRegistrationBean 并将其映射到特定的 URL

      How to add a filter class in Spring Boot?

      http://www.leveluplunch.com/blog/2014/04/01/spring-boot-configure-servlet-mapping-filters/

      【讨论】:

      • 是的,但是在方法上使用注释似乎更干净。有没有办法使用注释来做到这一点?
      • 感谢 Paul,但链接中提到的注解 (@Filter) 用于指定过滤器。我正在寻找的是我将在休息方法上放置的注释,以指定我希望将给定的过滤器应用于被注释的特定休息端点。我想我可以创建一个智能的 FilterRegistrationBean 来检查注释并相应地分配过滤器,只是希望它已经存在。
      • 我做了一些研究..我找不到任何能做到这一点的东西。
      猜你喜欢
      • 1970-01-01
      • 2013-05-18
      • 2018-07-05
      • 2017-11-24
      • 1970-01-01
      • 2015-04-09
      • 2019-10-01
      • 2019-04-14
      • 2015-10-19
      相关资源
      最近更新 更多