From within a servlet how do you access a variable set inside a corresponding servlet filter?
I'd like to use the following filter to open and close persistence managers.
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 {
m开发者_C百科anager = 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() {}
}
What I don't know is how to access the manager
variable from inside the corresponding servlet that gets called after this filter.
In the filter, put the manager as a request attribute:
request.setAttribute("persistenceManager", manager);
Then, in the servlet, it is accessible with:
PersistenceManager manager =
(PersistenceManager) request.getAttribute("persistenceManager");
精彩评论