springboot的FilterRegistrationBean增加过滤器

前言

如果按照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;
   }

你可能感兴趣的:(springboot)