1、直接使用过滤器不会生效@WebFilter(urlPatterns="/dd/*", filterName=“loginFilter”)
需要在springboot启动类上加上@ServletComponent注解才会生效(推荐这种方式)
/**
* @author nineee
* @description urlPatterns:拦截的url地址
* filterName:拦截器名称
* @date 2020/8/31 16:09
*/
@Slf4j
@WebFilter(urlPatterns="/dd/*", filterName="loginFilter")
public class LoginFilter implements Filter{
/*
* 容器加载完成调用
* */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("LoginFilter.init");
}
/*
* 请求被拦截的时候调用
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.info("LoginFilter.doFilter");
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
chain.doFilter(request, response);
}
/*
* 容器被销毁的时候调用
* */
@Override
public void destroy() {
System.out.println("filter destroy...");
}
}
@SpringBootApplication
@ServletComponentScan
public class NineeeStart {
public static void main(String[] args) {
SpringApplication.run(NineeeStart.class, args);
}
}
2、手动配置bean
不需要@WebFilter注解
/**
* @author nineee
* @description urlPatterns:拦截的url地址
* filterName:拦截器名称
* @date 2020/8/31 16:09
*/
@Slf4j
public class LoginFilter implements Filter{
/*
* 容器加载完成调用
* */
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("LoginFilter.init");
}
/*
* 请求被拦截的时候调用
* */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
log.info("LoginFilter.doFilter");
HttpServletRequest req = (HttpServletRequest)request;
HttpServletResponse resp = (HttpServletResponse)response;
chain.doFilter(request, response);
}
/*
* 容器被销毁的时候调用
* */
@Override
public void destroy() {
System.out.println("filter destroy...");
}
}
@Configuration
public class WebAuthFilterConfig {
@Bean
public FilterRegistrationBean webAuthFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(loginFilter());
registration.setName("LoginFilter");
registration.addUrlPatterns("/spu/*");
// registration.addInitParameter("excludeUrls", "/web/login");
registration.setOrder(0);
return registration;
}
@Bean
public Filter loginFilter() {
return new LoginFilter();
}
}
3、网上有的加上@Component注解@Configuration注解过滤器会生效,url会匹配全部,原因得去扒源码看。