这里是一些废话
- SpringBoot实现过滤器和SpringMVC上实现没有多大差别,主要的差别就是在过滤器注册上,SpringMVC是通过XML配置文件注册过滤器,而SpringBoot则是通过代码注解的形式进行注册。下面一起看下在SpringBoot上怎么实现Filter过滤器吧。
Filter过滤器具体实现类
@Component
public class AuthFilter implements Filter {
public static final String X_CLACKS_OVERHEAD = "X-Clacks-Overhead";
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader(X_CLACKS_OVERHEAD, "GNU Terry Pratchett");
chain.doFilter(req, res);
}
@Override
public void destroy() {}
@Override
public void init(FilterConfig arg0) throws ServletException {}
}
注册Filter过滤器
/**
* 自定义配置项类,该类中和存入拦截器、过滤器等配置项信息
* @author Administrator
*/
@Configuration
public class CustemConfigurerAdapter {
@Bean
public FilterRegistrationBean authFilterRegistrationBean() {
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setName("authFilter");
AuthFilter authFilter = new AuthFilter();
registrationBean.setFilter(authFilter);
registrationBean.setOrder(1);
List<String> urlList = new ArrayList<String>();
urlList.add("/*");
registrationBean.setUrlPatterns(urlList);
return registrationBean;
}
}
调试效果示意图