本篇通过配置类实现在SpringBoot中使用Filter,依旧复用Servlet中的代码。
一、新建一个fiter类实现Filter接口:
package cn.com.winson.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class MyFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("进入filter过滤器,请求正常,放行!"); chain.doFilter(request, response); } @Override public void destroy() { } }
二、配置类中配置过滤器规则:
package cn.com.winson.config; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import cn.com.winson.filter.MyFilter; import cn.com.winson.servlet.MyServlet; /*SpringBoot没有xml,@Configuration注解可以表示一个spring的xml配置文件*/ @Configuration public class ServletConfig { /* * @Bean注解:相当于Spring中的配置文件中的<bean>标签,下面的方法相当于如下配置:id为方法名,class为返回值 <bean * id="myServletRegistrationBean" * class="org.springframework.boot.web.servlet.ServletRegistrationBean;"> * </bean> */ @Bean public ServletRegistrationBean myServletRegistrationBean() { /* 将Servlet注册为一个bean,设置访问路径 */ ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet"); return registrationBean; } @Bean public FilterRegistrationBean myFilterRegistrationBean() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter()); filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } }
三、运行程序,访问结果:
四、控制台打印结果,包含字符串:证明过滤器生效了。
总结
一、方式方法同SpringBoot中使用Servlet。