Tomcat: how to access (session) Manager from servlet
for Tomcat:
ApplicationContextFacade appContextFacadeObj = (ApplicationContextFacade) request.getSession().getServletContext();
try
{
Field applicationContextField = appContextFacadeObj.getClass().getDeclaredField("context");
applicationContextField.setAccessible(true);
ApplicationContext appContextObj = (ApplicationContext) applicationContextField.get(appContextFacadeObj);
Field standardContextField = appContextObj.getClass().getDeclaredField("context");
standardContextField.setAccessible(true);
StandardContext standardContextObj = (StandardContext) standardContextField.get(appContextObj);
Manager persistenceManager = standardContextObj.getManager();
}
catch(SecurityException e)
{
logger.error(e);
}
catch(NoSuchFieldException e)
{
logger.error(e);
}
catch(IllegalArgumentException e)
{
logger.error(e);
}
catch(IllegalAccessException e)
{
logger.error(e);
}
As opposed to Ihor's code, this code uses a little less abstraction by getting Manager
from HttpSession
:
private Manager manager(HttpSession session) throws Exception {
Field facadeSessionField = StandardSessionFacade.class.getDeclaredField("session");
facadeSessionField.setAccessible(true);
StandardSession stdSession = (StandardSession) facadeSessionField.get(session);
return stdSession.getManager();
}