這篇文章主要講解了“Servlet中Filter的實現(xiàn)原理是什么”,文中的講解內(nèi)容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Servlet中Filter的實現(xiàn)原理是什么”吧!
創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務,包含不限于成都做網(wǎng)站、網(wǎng)站設計、南明網(wǎng)絡推廣、小程序制作、南明網(wǎng)絡營銷、南明企業(yè)策劃、南明品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供南明建站搭建服務,24小時服務熱線:18982081108,官方網(wǎng)址:www.cdcxhl.com
環(huán)境:Java8
Servlet中Filter使用的設計模式是責任鏈設計模式。我們可以定義一組Filter然后對數(shù)據(jù)進行依次的處理。責任鏈設計模式屬于行為型模式。UML圖如下:
Filter執(zhí)行流程如下:
接下來我們來實現(xiàn)一個Filter
Filter.java接口
public interface Filter { void doFilter(Request request, Response response, FilterChain chain) ; }
FilterChain.java 關鍵的調(diào)用鏈
public class FilterChain implements Filter{ private Listfilters = new ArrayList<>() ; private int position = 0 ; public void doFilter(Request request, Response response, FilterChain chain) { if (position > filters.size() - 1) { return ; } Filter filter = filters.get(this.position++) ; filter.doFilter(request, response, this) ; } // 構(gòu)建需要調(diào)用的Filter鏈 public FilterChain addFilter(Filter filter) { this.filters.add(filter) ; return this ; } }
Filter相關子類
public class LoginFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("LoginFilter entry...") ;
chain.doFilter(request, response, chain) ;
System.out.println("LoginFilter over...") ;
}
}
public class CharFilter implements Filter {
@Override
public void doFilter(Request request, Response response, FilterChain chain) {
System.out.println("CharFilter entry...") ;
chain.doFilter(request, response, chain) ;
System.out.println("CharFilter over...") ;
}
}
public class GrantFilter implements Filter { @Override public void doFilter(Request request, Response response, FilterChain chain) { System.out.println("GrantFilter entry...") ; chain.doFilter(request, response, chain) ; System.out.println("GrantFilter over...") ; } }
客戶端
public static void main(String[] args) { LoginFilter loginFilter = new LoginFilter() ; CharFilter charFilter = new CharFilter() ; GrantFilter grantFilter = new GrantFilter() ; FilterChain chain = new FilterChain() ; chain.addFilter(loginFilter).addFilter(charFilter).addFilter(grantFilter) ; Request request = new Request() ; Response response = new Response() ; chain.doFilter(request, response, null) ; }
運行結(jié)果
按照添加Filter順序,請求時先添加的先執(zhí)行,返回時后添加的Filter先執(zhí)行。java web中的Filter不也是這樣么!!!
感謝各位的閱讀,以上就是“Servlet中Filter的實現(xiàn)原理是什么”的內(nèi)容了,經(jīng)過本文的學習后,相信大家對Servlet中Filter的實現(xiàn)原理是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關知識點的文章,歡迎關注!