您好,登錄后才能下訂單哦!
這篇文章主要講解了“Servlet中Filter的實現原理是什么”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“Servlet中Filter的實現原理是什么”吧!
環境:Java8
Servlet中Filter使用的設計模式是責任鏈設計模式。我們可以定義一組Filter然后對數據進行依次的處理。責任鏈設計模式屬于行為型模式。UML圖如下:
Filter執行流程如下:
接下來我們來實現一個Filter
Filter.java接口
public interface Filter { void doFilter(Request request, Response response, FilterChain chain) ; }
FilterChain.java 關鍵的調用鏈
public class FilterChain implements Filter{ private List<Filter> filters = 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) ; } // 構建需要調用的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) ; }
運行結果
按照添加Filter順序,請求時先添加的先執行,返回時后添加的Filter先執行。java web中的Filter不也是這樣么!!!
感謝各位的閱讀,以上就是“Servlet中Filter的實現原理是什么”的內容了,經過本文的學習后,相信大家對Servlet中Filter的實現原理是什么這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。