在 Spring Boot 应用程序中添加 Servlet 过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26151057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:06:33  来源:igfitidea点击:

Add a Servlet Filter in a Spring Boot application

springannotationsservlet-filtersspring-boot

提问by dVaffection

I'd like to have ETag suport. For this purpose there is a ShallowEtagHeaderFilterwhich does all the work. How can I add it without declaring it in my web.xml(which actually does not exist, because I somehow got by without it so far)?

我想要ETag 支持。为此,有一个ShallowEtagHeaderFilter可以完成所有工作的。如何在不声明它的情况下添加它web.xml(实际上并不存在,因为到目前为止我以某种方式没有它)?

P.S. I use Spring Boot 1.1.4

PS我使用Spring Boot 1.1.4

P.P.S. Here's a full solution

PPS 这是一个完整的解决方案

package cuenation.api;

import org.springframework.boot.context.embedded.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.ShallowEtagHeaderFilter;

import javax.servlet.DispatcherType;
import java.util.EnumSet;

@Configuration
public class WebConfig {

    @Bean
    public FilterRegistrationBean shallowEtagHeaderFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new ShallowEtagHeaderFilter());
        registration.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));
        registration.addUrlPatterns("/cue-categories");
        return registration;
    }

}

回答by Brian Clozel

When using Spring Boot

使用 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!

正如参考文档中提到的,唯一需要的步骤是在配置类中将该过滤器声明为一个 Bean,就是这样!

@Configuration
public class WebConfig {

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

When using Spring MVC

使用 Spring MVC 时

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

您可能已经在扩展WebApplicationInitializer. 如果没有,那么您应该将您的 webapp 配置从web.xml文件转换为WebApplicationInitializer类。

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

如果您的上下文配置存在于 XML 文件中,您可以创建一个扩展类AbstractDispatcherServletInitializer- 如果使用配置类,AbstractAnnotationConfigDispatcherServletInitializer则是正确的选择。

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.

Spring 参考文档中提供了基于代码的 Servlet 容器初始化的完整示例。

回答by Andrii Abramov

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

查看更多:@AliasForSpring自定义注解问题