在 Spring Boot 应用程序中添加 Servlet 过滤器 [英] Add a Servlet Filter in a Spring Boot application

查看:53
本文介绍了在 Spring Boot 应用程序中添加 Servlet 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 web.xml (which actually does not exist, because I somehow got by without it so far)?

附言我使用的是 Spring Boot 1.1.4

P.S. I use Spring Boot 1.1.4

P.P.S.这是一个完整的解决方案

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

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;
    }

}

推荐答案

使用 Spring Boot 时

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

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();
  }
}

使用 Spring MVC 时

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

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.

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

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();
    };
  }

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

这篇关于在 Spring Boot 应用程序中添加 Servlet 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆