欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springboot的FilterRegistrationBean增加过滤器

程序员文章站 2022-03-10 10:45:13
前言如果按照j2ee的规范,需要增加Filter的话,要实现Filter接口,然后在web.xml里面配置Filter。现在springboot已经将所有动作封装好。我们只要@Bean 增加FilterRegistrationBean类定义即可增加一个过滤器。自定义Filterpublic class ReplaceStreamFilter implements Filter { private static final Logger log = LoggerFactory.getLogger(...

前言

如果按照j2ee的规范,需要增加Filter的话,要实现Filter接口,然后在web.xml里面配置Filter。现在springboot已经将所有动作封装好。我们只要@Bean 增加FilterRegistrationBean类定义即可增加一个过滤器。

自定义Filter

public class ReplaceStreamFilter implements Filter {
   private static final Logger log = LoggerFactory.getLogger(ReplaceStreamFilter.class);

   public void init(FilterConfig filterConfig) throws ServletException {
      log.info("StreamFilter初始化...");
   }

   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
      ServletRequest requestWrapper = new RequestWrapper((HttpServletRequest)request);
      chain.doFilter(requestWrapper, response);
   }

   public void destroy() {
      log.info("StreamFilter销毁...");
   }
}

将Filter进行实例化并自动配置

@Bean
   public FilterRegistrationBean<Filter> replaceStreamFilter() {
      FilterRegistrationBean<Filter> registrationBean = new FilterRegistrationBean();
      registrationBean.setFilter(new ReplaceStreamFilter());//添加Filter实现类
      registrationBean.addUrlPatterns(new String[]{"/*"});//匹配路径
      registrationBean.setOrder(1);//优先级
      return registrationBean;
   }

本文地址:https://blog.csdn.net/keyingbo2008/article/details/107687096

相关标签: springboot