1、概述
springboot工程中使用Filter过滤器与其他地方使用基本相同,只是注入的方式不同。
2、创建Filter过滤器
实现Filter接口,重写doFilter方法
filterChain.doFilter(servletRequest,servletResponse);表示放行
public class MyFilter implements Filter {@Overridepublic void init(FilterConfig filterConfig) throws ServletException {}@Overridepublic void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {System.out.println("=======过滤器执行========");filterChain.doFilter(servletRequest,servletResponse);}@Overridepublic void destroy() {}
}
3、向容器中注册自定义的Filter
@Configuration
public class MyServerConfig {//注册三大组件--Filter@Beanpublic FilterRegistrationBean myFilter(){FilterRegistrationBean filter=new FilterRegistrationBean();filter.setFilter(new MyFilter());filter.setUrlPatterns(Arrays.asList("/getUser","/myservlet"));return filter;}}