菜鳥の道——Spring MVC(11)Conttext Loader Listenerロード配置ファイル

2875 ワード

Conttext Loader Listenerの役割:Web容器を起動する際に、Spring appration Controtext.xmlの配置情報を自動的に組み立てる。
Servlet Contactext Listenerというインターフェースを実現しているので、web.xmlにこのモニターを配置し、容器を起動すると、デフォルトでその実現方法を実行します。Conttext Loader ListenerにContect Loaderというクラスが関連していますので、全体のロード構成過程はContect Loaderによって完成されます。
 
//     ServletContextListener,         contextDestroyed, contextInitialized     

public class ContextLoaderListener implements ServletContextListener{

       private ContextLoader contextLoader;

       /**

       *Initialize the root web application context.

       */

      //Spring      , contextInitialized        main    

       public void contextInitialized(ServletContextEvent event) {

             this.contextLoader = createContextLoader();

             this.contextLoader.initWebApplicationContext(event.getServletContext());

       }

       /**

       * Createthe ContextLoader to use. Can be overridden in subclasses.

       * @returnthe new ContextLoader

      */                                           

       protected ContextLoader createContextLoader() {

             return new ContextLoader();

       }

       /**

       * Returnthe ContextLoader used by this listener.

       * @returnthe current ContextLoader

       */

       public ContextLoader getContextLoader() {

             return this.contextLoader;

       }

       /**

       * Closethe root web application context.

       */

       public void contextDestroyed(ServletContextEvent event) {

             if (this.contextLoader != null) {

                    this.contextLoader.closeWebApplicationContext(event.getServletContext());

             }

       }

}
 
  全体的にこの入り口はとても簡単で、すべての実現はContect Loader類に隠れています。  ServletContect ListenerはServlet Contectの傍受者であり、もしServlet Contectが変化したら、サーバーが起動した時にServlet Contectが作成され、サーバーがオフした時にServlet Contextが破壊されます。  JSPファイルでは、aplicationはServlet Contectの例であり、JSP容器によってデフォルトで作成されます。Servletでget Servlet Contect()を呼び出す方法は、Servlet Contectの例を得る。  キャッシュを使っています。  1.サーバーが起動する時、Servlet Contect Listenerのcontext Initialized()メソッドが呼び出されますので、中にキャッシュを作成します。キャッシュ内容生成クラスはファイルから読み込むか、データベースから読み込むことができ、ServletContact.set Attribute()方法でキャッシュクラスをServlet Contectの例に保存します。  2.プログラムはServlet Contect.get Attribute()を使ってキャッシュを読みだします。JSPなら、アプリアプリ・get Attribute()を使います。Servletであれば、get Servlet Contect().get Attribute()を使用します。キャッシュが変化したら(アクセスカウントなど)、キャッシュとファイル/データベースを同時に変更できます。あるいは変化を待って一定のプログラムに蓄積して保存してもいいです。次のステップで保存できます。  3.サーバがクローズします。ServletContactext Listenerのcontext Destroyed()方法が呼び出されますので、キャッシュの変更を中に保存します。変更されたキャッシュをファイルまたはデータベースに保存し、元の内容を更新します。
  Servlet Contectは、Webコンテナと通信するためにServletプログラムによって使用される。例えばログを書いたり、転送要求をしたりします。各WebアプリケーションにはContectが含まれており、Webアプリケーション内の各プログラムで共有されています。Contextは資源を保存して共有できるので、私が知っているServlet Controtextの最大のアプリケーションはWebキャッシュです。頻繁に変更しない内容をメモリに読み込むので、サーバーが要求に応答する時は低速ディスクI/Oを行う必要はありません。