Tomcat為什么要使用Facde模式對Request對象進行包裝?


為了屏蔽內部catalina容器的相關方法,使用戶免受非servlet標准方法的干擾。
tomcat中request的包裝結構:
 
 

其中org.apache.coyote.Request是應用層拿到的Request對象的底層實現,不便使用,tomcat80/Request.java at trunk · apache/tomcat80 · GitHub
/**
 * This is a low-level, efficient representation of a server request. Most
 * fields are GC-free, expensive operations are delayed until the  user code
 * needs the information.
 *
 * Processing is delegated to modules, using a hook mechanism.
 *
 * This class is not intended for user code - it is used internally by tomcat
 * for processing the request in the most efficient way. Users ( servlets ) can
 * access the information using a facade, which provides the high-level view
 * of the request.
 *
 * Tomcat defines a number of attributes:
 * <ul>
 *   <li>"org.apache.tomcat.request" - allows access to the low-level
 *       request object in trusted applications
 * </ul>
 *
 * @author James Duncan Davidson [duncan@eng.sun.com]
 * @author James Todd [gonzo@eng.sun.com]
 * @author Jason Hunter [jch@eng.sun.com]
 * @author Harish Prabandham
 * @author Alex Cruikshank [alex@epitonic.com]
 * @author Hans Bergsten [hans@gefionsoftware.com]
 * @author Costin Manolache
 * @author Remy Maucherat
 */


org.apache.catalina.connector.Request類(tomcat80/Request.java at trunk · apache/tomcat80 · GitHub)封裝了org.apache.coyote.Request類,實現了HttpServletRequest接口,已經具備了實際使用能力,不過它還包含了很多Catalina的方法,,這些方法不應該暴露給應用層,以免引起與其他容器實現的兼容性問題。

org.apache.catalina.connector.RequestFacade類(tomcat80/RequestFacade.java at trunk · apache/tomcat80 · GitHub)實現了HttpServletRequest接口,並在其中包含了一個org.apache.catalina.connector.Request對象,將所有HttpServletRequest接口的調用,都代理給org.apache.catalina.connector.Request對象來處理,這樣就屏蔽了Catalina的相關的內部方法,使用戶可以專注於servlet的標准方法。

從org.apache.catalina.connector.RequestFacade這個類,我們可以看到,這是一個使用了fa?ade模式的包裝類,所以我們需要先了解一下fa?ade模式的相關知識。
Fa?ade模式介紹
facade模式的核心是為子系統的一組接口提供一個統一的界面,方便客戶端使用子系統,客戶端也不必關心子系統的具體實現。
facade設計模式的適用情況:
1. 原來的類提供的接口比較多,也比較復雜,而我們只需要使用其部分接口;
2. 原類提供的接口只能部分的滿足我們的需要,且不希望重寫一個新類來代替原類;
...
在本文中,RequestFacade是對Request的一個封裝,由於Request本身提供的接口非常之多,而本系統中只需要使用其部分功能,在實際分析過程中,我們發現Request的具體工作最后delegate到底層的coyote.Request去做。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM