目录
原生注解
1:添加注解,实现接口
@WebFilter(urlPatterns = "/*")
public class TIFAuthenticationFilter implements Filter {}
2:启动类上加注解
@ServletComponentScan
boot方式
点击查看代码
import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
public class TestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("TestFilter过滤器 方法执行前...");
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
System.out.println("TestFilter过滤器 方法执行后...");
}
}
//配置config
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FilterConfig {
@Bean
public FilterRegistrationBean testFilter(){
FilterRegistrationBean filterRegistry = new FilterRegistrationBean();
filterRegistry.setFilter(new TestFilter());
filterRegistry.setOrder(1);
filterRegistry.setName("testFilter");
filterRegistry.addUrlPatterns("/*");
return filterRegistry;
}
}