1,实现 Filter 接口,重写init 方法
public class AdminLoginFilter implements Filter {
static Log logger = LogFactory.getLog(AdminLoginFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
logger.debug("logger过滤器的init执行");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
logger.debug("logger过滤器doFilter开始执行");
filterChain.doFilter(servletRequest, servletResponse);
logger.debug("logger接口执行完毕");
}
@Override
public void destroy() {
}
}
2,Configuration 标记为配置类, bean方式注入 FilterRegistrationBean 到ioc容器
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean registFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new AdminLoginFilter());
registration.addUrlPatterns("/*"); //url的匹配模式
registration.setName("LogCostFilter"); //过滤器名称
registration.setOrder(1); //执行顺序
return registration;
}
}