2010-09-20 52 views
2

我想使用以下過濾器來打開和關閉持久性管理器。從一個servlet中,你如何訪問相應servlet過濾器中的變量集?

public final class PersistenceFilter implements Filter { 
    private static final PersistenceManagerFactory persistenceManagerFactory 
     = JDOHelper.getPersistenceManagerFactory("transactions-optional"); 

    private static PersistenceManagerFactory factory() { 
     return persistenceManagerFactory; 
    } 

    private static ThreadLocal currentManager = new ThreadLocal(); 

    public static PersistenceManager getManager() { 
     if (currentManager.get() == null) { 
      currentManager.set(factory().getPersistenceManager()); 
     } 
     return currentManager.get(); 
    } 
    @Override 
    public void doFilter(ServletRequest req, ServletResponse res, 
      FilterChain chain) throws IOException, ServletException { 
     PersistenceManager manager = null; 
     try { 
      manager = getManager(); 
      //Optional: allow all persistent objects implementing a custom interface 
      //to be notified of when they are saved and loaded. 
      manager.addInstanceLifecycleListener(new PersistHookListener(), PersistHooks.class); 
      chain.doFilter(req, res); 
     } finally { 
      if (manager != null) { 
       manager.flush(); 
       manager.close(); 
      } 
     } 
    } 
    @Override 
    public void init(FilterConfig arg0) throws ServletException {} 
    @Override 
    public void destroy() {} 
} 

我不知道的是如何從被該過濾器後調用相應的servlet的內部訪問manager變量。

回答

3

在過濾器,把管理作爲一個請求屬性:

request.setAttribute("persistenceManager", manager); 

然後,在servlet,它是與訪問:

PersistenceManager manager = 
    (PersistenceManager) request.getAttribute("persistenceManager");