SpringBoot整合Filter
方式与整合Servlet类似
- 方式一、通过方法注册的形式
filter
public class MyFilter 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("进入filter");
filterChain.doFilter(servletRequest,servletResponse);
System.out.println("离开filter");
}
@Override
public void destroy() {
}
}
启动类
@SpringBootApplication
public class CrmApplication {
public static void main(String[] args) {
SpringApplication.run(CrmApplication.class, args);
}
@Bean
public ServletRegistrationBean get(){
ServletRegistrationBean bean=new ServletRegistrationBean(new MyServlet());
bean.addUrlMappings("/second");
return bean;
}
@Bean
public FilterRegistrationBean getFilter(){
FilterRegistrationBean bean=new FilterRegistrationBean(new MyFilter());
bean.addUrlPatterns("/second");
return bean;
}
}
- 方式二、通过注解的方式,与整合Servlet一样
@WebFilter(filterName="MyFilter",urlPatterns="/first")