Java過濾器Filter詳解
阿新 • • 發佈:2021-08-26
目錄
- Filter學習
- Filter功能
- Filter的工作原理
- 多個Filter的實現
- Filter的執行邏輯
- 總結
Filter學習
Filter功能
- 攔截pwww.cppcns.com、靜態圖片檔案、靜態html資原始檔
- 實現URL級別的許可權訪問控制
- 過濾敏感詞彙
- 壓縮相應資訊
Filter的工作原理
看原始碼可以看出來,Filter介面中有3個方法:init、doFilter、destory
init方法,初始化Filter,Filter在伺服器啟動階段被例項化。並且呼叫init方法,init方法只執行一次,因為Filter只被例項化一次。
destory方法也好理解,就是銷燬Filter,釋放記憶體,在執行結束時呼叫此方法當。長時間沒有使用者訪問,或者專案重新部署,或者伺服器重新啟動的時候,會銷燬所有的Filter物件,銷燬之前會先呼叫Filter物件的destroy方法,完成銷燬前的準備工作。也是隻執行一次。
doFilter方法提供給開發者重寫過濾邏輯。
多個Filter的實現
public class AFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("輸出filter2的init方法"); } @Override public void doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain) throws IOException,ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletRequest request = (HttpServletRequest) servletRequest;System.out.println("輸出filter2的doFilter方法之前"); filterChain.doFilter(request,www.cppcns.comresponse); System.out.println("輸出filter2的doFilter方法之後"); } @Override public void destroy() { System.out.println("輸出filter2的destroy方法"); } }
public class BFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("輸出filter1的init方法"); } @Override public void doFilter(ServletRequest servletRequest,ServletException { HttpServletResponse response = (HttpServletResponse) servletResponse; HttpServletRequest request = (HttpServletRequest) servletRequest; System.out.println("輸出filter1的doFilter方法之前");http://www.cppcns.comfilterChain.doFilter(request,response); System.out.println("輸出filter1的doFilter方法之後"); } @Override public void destroy() { System.out.printlnwww.cppcns.com("輸出filter1的destroy方法"); } }
配置Filter的過濾順序,通過setOrder方法執行FilterChain的順序,數字越小,優先順序越高。
@Configuration public class WebConfig { @Bean public FilterRegistrationBean filter1() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); AFilter aFilter = new AFilter(); filterRegistrationBean.setFilter(aFilter); filterRegistrationBean.setOrder(1); return filterRegistrationBean; } @Bean public FilterRegistrationBean filter2() { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); BFilter bFilter = new BFilter(); filterRegistrationBean.setFilter(bFilter); filterRegistrationBean.setOrder(2); return filterRegistrationBean; } }
Filter的執行邏輯
總結
本篇文章就到這裡了,希望能給你帶來幫助,也希望您能夠多多關注我們的更多內容!