前言
传统的javaEE增加Filter是在web.xml中配置,如以下代码:
TestFiltercom.cppba.filter.TestFilterTestFilter/*paramNameparamValue
然而spring-boot中很明显不能这样实现,那怎么办呢?看完下面的教程,答案自然知道了。
老方法(新方法请直接下拉)
1.创建自定义Filter
packagecom.cppba.filter;importjavax.servlet.*;importjava.io.IOException;publicclassTestFilterimplementsFilter{@Overridepublicvoidinit(FilterConfig filterConfig)throwsServletException{ }@OverridepublicvoiddoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throwsIOException, ServletException{ System.out.println("TestFilter"); }@Overridepublicvoiddestroy(){ }}
2.在ApplicationConfiguration.java中增加一个@bean
@BeanpublicFilterRegistrationBeantestFilterRegistration(){ FilterRegistrationBean registration =newFilterRegistrationBean(); registration.setFilter(newTestFilter()); registration.addUrlPatterns("/*"); registration.addInitParameter("paramName","paramValue"); registration.setName("testFilter"); registration.setOrder(1);returnregistration; }
3.启动项目
你会看到控制台打印如下代码:
https://github.com/bigbeef/cppba-spring-boot
4.访问项目
最后我们访问以下http://127.0.0.1:8080/test
如果你看到控制台打印出:TestFilter
https://github.com/bigbeef/cppba-spring-boot
恭喜你,配置成功!
参考项目:https://github.com/bigbeef/cppba-spring-boot
github地址:https://github.com/bigbeef
个人博客:http://www.cppba.com
2017-04-20 最新spring-boot增加Filter方法
首先定义一个Filter
@Order(1)//重点@WebFilter(filterName ="testFilter1", urlPatterns ="/*")publicclassTestFilterFirstimplementsFilter{@Overridepublicvoidinit(FilterConfig filterConfig)throwsServletException{ }@OverridepublicvoiddoFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)throwsIOException, ServletException{ System.out.println("TestFilter1"); filterChain.doFilter(servletRequest,servletResponse); }@Overridepublicvoiddestroy(){ }}
比较核心的代码是自定义类上面加上@WebFilter,其中@Order注解表示执行过滤顺序,值越小,越先执行
我们在spring-boot的入口处加上如下注解@ServletComponentScan:
@SpringBootApplication(scanBasePackages ="com.cppba")//重点@ServletComponentScanpublicclassApplication{publicstaticvoidmain(String[] args)throwsUnknownHostException{ SpringApplication app =newSpringApplication(Application.class); Environment environment = app.run(args).getEnvironment(); }}
这种方法效果和上面版本一样,但是用起来更加方便!
作者:大黄蜂coder
链接:http://www.jianshu.com/p/05c8be17c80a
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
参考项目:https://github.com/bigbeef/cppba-spring-boot