前言
傳統(tǒng)的javaEE增加Filter是在web.xml中配置恕曲,如以下代碼:
TestFiltercom.cppba.filter.TestFilterTestFilter/*paramNameparamValue
然而spring-boot中很明顯不能這樣實(shí)現(xiàn),那怎么辦呢瀑凝?看完下面的教程灵奖,答案自然知道了蚊丐。
老方法(新方法請(qǐng)直接下拉)
1.創(chuàng)建自定義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中增加一個(gè)@bean
@BeanpublicFilterRegistrationBeantestFilterRegistration(){? ? ? ? FilterRegistrationBean registration =newFilterRegistrationBean();? ? ? ? registration.setFilter(newTestFilter());? ? ? ? registration.addUrlPatterns("/*");? ? ? ? registration.addInitParameter("paramName","paramValue");? ? ? ? registration.setName("testFilter");? ? ? ? registration.setOrder(1);returnregistration;? ? }
3.啟動(dòng)項(xiàng)目
你會(huì)看到控制臺(tái)打印如下代碼:
https://github.com/bigbeef/cppba-spring-boot
4.訪問(wèn)項(xiàng)目
最后我們?cè)L問(wèn)以下http://127.0.0.1:8080/test
如果你看到控制臺(tái)打印出:TestFilter
https://github.com/bigbeef/cppba-spring-boot
恭喜你射富,配置成功!
參考項(xiàng)目:https://github.com/bigbeef/cppba-spring-boot
github地址:https://github.com/bigbeef
個(gè)人博客:http://www.cppba.com
2017-04-20 最新spring-boot增加Filter方法
首先定義一個(gè)Filter
@Order(1)//重點(diǎn)@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(){? ? }}
比較核心的代碼是自定義類(lèi)上面加上@WebFilter析恢,其中@Order注解表示執(zhí)行過(guò)濾順序查刻,值越小键兜,越先執(zhí)行
我們?cè)趕pring-boot的入口處加上如下注解@ServletComponentScan:
@SpringBootApplication(scanBasePackages ="com.cppba")//重點(diǎn)@ServletComponentScanpublicclassApplication{publicstaticvoidmain(String[] args)throwsUnknownHostException{? ? ? ? SpringApplication app =newSpringApplication(Application.class);? ? ? ? Environment environment = app.run(args).getEnvironment();? ? }}
這種方法效果和上面版本一樣,但是用起來(lái)更加方便赖阻!
作者:大黃蜂coder
鏈接:http://www.reibang.com/p/05c8be17c80a
來(lái)源:簡(jiǎn)書(shū)
著作權(quán)歸作者所有蝶押。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系作者獲得授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處火欧。
參考項(xiàng)目:https://github.com/bigbeef/cppba-spring-boot
開(kāi)源地址:https://github.com/bigbeef
個(gè)人博客:http://blog.cppba.com