Add a Servlet Filter in a Spring Boot application

前端 未结 2 1379
清酒与你
清酒与你 2020-12-01 11:57

I\'d like to have ETag suport. For this purpose there is a ShallowEtagHeaderFilter which does all the work. How can I add it without declaring it in my we

相关标签:
2条回答
  • 2020-12-01 12:37

    When using Spring Boot

    As mentioned in the reference documentation, the only step needed is to declare that filter as a Bean in a configuration class, that's it!

    @Configuration
    public class WebConfig {
    
      @Bean
      public Filter shallowEtagHeaderFilter() {
        return new ShallowEtagHeaderFilter();
      }
    }
    

    When using Spring MVC

    You're probably already extending a WebApplicationInitializer. If not, then you should convert your webapp configuration from a web.xml file to a WebApplicationInitializer class.

    If your context configuration lives in XML file(s), you can create a class that extends AbstractDispatcherServletInitializer - if using configuration classes, AbstractAnnotationConfigDispatcherServletInitializer is the proper choice.

    In any case, you can then add Filter registration:

      @Override
      protected Filter[] getServletFilters() {
        return new Filter[] {
          new ShallowEtagHeaderFilter();
        };
      }
    

    Full examples of code-based Servlet container initialization are available in the Spring reference documentation.

    0 讨论(0)
  • 2020-12-01 12:51

    A bit late answer.

    My solution was to create custom annotation:

    import org.springframework.core.annotation.AliasFor;
    import org.springframework.stereotype.Component;
    
    // ...
    
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    @Component
    public @interface Filter {
    
        @AliasFor(annotation = Component.class, attribute = "value")
        String value() default "";
    
    }
    

    And then simply apply it to the filter implementations:

    @Filter
    public class CustomFilter extends AbstractRequestLoggingFilter {
    
        @Override
        protected void beforeRequest(HttpServletRequest request, String message) {
            logger.debug("before req params:", request.getParameterMap());
        }
    
        @Override
        protected void afterRequest(HttpServletRequest request, String message) {
            logger.debug("after req params:", request.getParameterMap());
        }
    }
    

    See more: @AliasFor, Spring custom annotations question

    0 讨论(0)
提交回复
热议问题