Friday, March 30, 2012

Sharing Liferay's Portal ClassLoader

It is possible to share Liferay Portal's ClassLoader with Liferay's plugins (eg. Portlets WARs and also independent Servlets)

Say if I have a Servlet called Servlet1 that was packaged in a separate WAR that I'd like to use Liferay Portal's classloader, I'd need to declare it as a PortalClassLoaderServlet through the following configurations in it's web.xml

  
    PortalClassLoaderServlet
    com.liferay.portal.kernel.servlet.PortalClassLoaderServlet
    
       servlet-class
       foo.bar.Servlet1
    
    100
  
  
     PortalClassLoaderServlet
     /servlet1/*
  

With this declaration and with Liferay deployed as a separate WAR file, Servlet1 will be registered when Liferay starts up and is aware of Liferay Portal's lifecycle, and will get initialized and destroyed (through Servlet's init(ServletConfig) and destroy() methods respectively) when Liferay Portal startup and shutdown). When a request is being made to Servlet1, PortalClassLoaderServlet will act as a proxy that swaps the current request thread's context ClassLoader with the ClassLoader that Liferay Portal is started up with and so you get all the classes that comes with Liferay Portal.

Technically, i think it is possible to take this further and having PortalServlet loaded using the same classloader as Liferay Portal through the following web.xml configuration

  
     MyPortal Servlet
     com.liferay.portal.kernel.servlet.PortalClassLoaderServlet
     
        servlet-class
        com.liferay.portal.kernel.servlet.PortletServlet
     
     
        portlet-class
        foo.bar.portlets.MyPortlet
     
     100
  

But care must be taken to make sure classes that was used also exists in Liferay Portal WAR or in say Tomcat's public library classpath. Messing with ClassLoader is always hazardous and best to be avoided if possible. That's my 2 cents.

No comments:

Post a Comment