Servlet,Listener和Filter 獲取ServletContext (application上下文環境)

Listener的項目上下文(既ServletContext既application)是從event中獲取的,event是Listener和容器之間交流的中間人

Java代碼  收藏代碼
  1. public interface ServletContextListener extends EventListener {     
  2.      
  3.     
  4.     public void contextInitialized ( ServletContextEvent sce );     
  5.     
  6.     
  7.     
  8. --------------------------------------------     
  9.     
  10.  ServletContext servletContext;     
  11.     
  12.     
  13.    public void contextInitialized(ServletContextEvent sce)     
  14.    {     
  15.       servletContext = sce.getServletContext();     
  16.    }  

 

 

而Filter的項目上下文(既ServletContext既application)是從FilterConfig中獲取的,FilterConfig是Filter和容器之間交流的中間人

 

Java代碼  收藏代碼
  1. public interface Filter {     
  2.     
  3.        
  4.     public void init(FilterConfig filterConfig) throws ServletException;     
  5.          
  6.     
  7.     
  8. ------------------------     
  9. filterConfig.getServletContext()   

 

 

而Servlet的項目上下文(既ServletContext既application)是從ServletConfig中獲取的,ServletConfig是Servlet和容器之間交流的中間人

 

Java代碼  收藏代碼
  1. public interface Servlet {     
  2.     
  3.       
  4.     
  5.     public void init(ServletConfig config) throws ServletException;     
  6.          
  7. ---------------------------------------     
  8.     
  9.  getServletConfig().getServletContext()  

 

我們的應用程序組件只能被動的遵守一定的規則,和容器打交道,和其他組件通信,也必須藉助於容器的力量。這裏面其實已經有一點控制反轉的味道,既然是組件生活在容器中,就必須被動的接受容器餵給他吃的東西,不能(要)自己創造(new)。

 

Spring之所以稱爲容器(號稱輕量級),就是因爲被他控制的組件,被動的吃他餵過來的東西,不能(要)自己創造(new)。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章