簡體   English   中英

同一個tomcat的webapps之間的共享對象

[英]shared objects between webapps of the same tomcat

我有2個webapps在兩個上下文中運行:c1,c2(都緊跟在root之后)。 我把一個startupListener放在c1中共享一個變量,另一個放在c2中來檢索它。

我在c1中的startuplistener是:

 public void contextInitialized(ServletContextEvent sce) {  
            HashMap <String,Object> database ;
            //some code to init database 
            ServletContext context = sce.getServletContext().getContext("/c1");
            if (context!=null)
            {
                context.setAttribute("crossContext", true);
                context.setAttribute("cache", database);
            }

    }

在c2應用程序中,它是這樣的:

      public void contextInitialized(ServletContextEvent sce) {
            ServletContext context = sce.getServletContext().getContext("/c1");
            HashMap<String,Object> database = (HashMap) context.getAttribute("cache");

      }

c2的startupListener中的上下文總是為null,我試過'/ c1','c1'。 我錯過了什么? (我正在使用tomcat6,如果重要的話)謝謝

您需要設置crossContext = true。 來自tomcat文檔:

如果要在此應用程序中調用ServletContext.getContext()以成功返回在此虛擬主機上運行的其他Web應用程序的請求調度程序,則設置為true。 在安全意識環境中設置為false(默認值),以使getContext()始終返回null。

http://tomcat.apache.org/tomcat-7.0-doc/config/context.html

問題:

應用初始化不匹配可能是app1在app1之前初始化。

有一個潛在的“解決方法”:如果您實際上有兩個(或更多)應用程序相互依賴,您可能決定在server.xml:啟動多個服務server.xml:

<Service name="app1">
  <Connector .../>

  <Engine ...>
     <Host appbase="app1" ...>
       ...        
     </Host>
  </Engine>
</Service>
<Service name="app2">
  <Connector .../>

  <Engine ...>
     <Host appbase="app2" ...>
       ...        
     </Host>
  </Engine>
</Service>

還有一個選擇是使用序列化。 在一個應用程序中序列化數據,在另一個應用程序中讀取相同的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM