我想使用以下过滤器来打开和关闭持久性管理器。
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
变量。
答案 0 :(得分:3)
在过滤器中,将管理器作为请求属性:
request.setAttribute("persistenceManager", manager);
然后,在servlet中,可以通过以下方式访问它:
PersistenceManager manager =
(PersistenceManager) request.getAttribute("persistenceManager");