这里是一些废话

  • SpringBoot实现过滤器和SpringMVC上实现没有多大差别,主要的差别就是在过滤器注册上,SpringMVC是通过XML配置文件注册过滤器,而SpringBoot则是通过代码注解的形式进行注册。下面一起看下在SpringBoot上怎么实现Filter过滤器吧。

Filter过滤器具体实现类

  1. @Component
  2. public class AuthFilter implements Filter {
  3. public static final String X_CLACKS_OVERHEAD = "X-Clacks-Overhead";
  4. @Override
  5. public void doFilter(ServletRequest req, ServletResponse res,
  6. FilterChain chain) throws IOException, ServletException {
  7. HttpServletResponse response = (HttpServletResponse) res;
  8. response.setHeader(X_CLACKS_OVERHEAD, "GNU Terry Pratchett");
  9. chain.doFilter(req, res);
  10. }
  11. @Override
  12. public void destroy() {}
  13. @Override
  14. public void init(FilterConfig arg0) throws ServletException {}
  15. }

注册Filter过滤器

  1. /**
  2. * 自定义配置项类,该类中和存入拦截器、过滤器等配置项信息
  3. * @author Administrator
  4. */
  5. @Configuration
  6. public class CustemConfigurerAdapter {
  7. @Bean
  8. public FilterRegistrationBean authFilterRegistrationBean() {
  9. FilterRegistrationBean registrationBean = new FilterRegistrationBean();
  10. registrationBean.setName("authFilter");
  11. AuthFilter authFilter = new AuthFilter();
  12. registrationBean.setFilter(authFilter);
  13. registrationBean.setOrder(1);
  14. List<String> urlList = new ArrayList<String>();
  15. urlList.add("/*");
  16. registrationBean.setUrlPatterns(urlList);
  17. return registrationBean;
  18. }
  19. }

调试效果示意图

【20180928】SpringBoot   Filter添加Header头 - 图1