Using custom java classes in a JSP hook - A different approach

How can you access custom classes within a JSP hook? Simple answer: you can't. Period.

JSPs in a hook are running in the portal classloader, while your custom classes are running in the hook context classloader. So the JSP in the portal classloader does not know about your custom classes.

In 2013 Kan Zhang wrote a blog post about how to use custom classes in a JSP hook. However his approaches all try to get the custom class into the global classloader or use a workaround by involving custom struts actions.

I would like to give a different approach.

Move the JSP to the hook context classloader

If the mountain won't come to Muhammad, Muhammad must go to the mountain

So I suggest to get the JSP into the hook context classloader instead of trying to get the custom class into the global classloader.

A litte drawback is that you need two JSPs instead of one. 

Step 1: Include a JSP from the hook context within the JSP hook

In a JSP hook we just include a second JSP using the liferay-util:include Tag. We have to pass the servletContext of the custom hook context.

<%
    ServletContext hookContext = ServletContextPool.get("my-sample-hook");
    if (hookContext != null) {
%>
        <liferay-util:include page="/html/hook.jsp" servletContext="<%=hookContext%>" />
<%
    }
%>
 

Step 2: Write a JSP inside your hook and use your custom class

When you write a JSP inside your hook (which is outside the directory you declare in custom-jsp-dir in your liferay-hook.xml) you have full access to the classes within your hook.

<p>
  Hello world from <%=MyCustomClass.getHelloWorld()%>
</p>

Final Remarks

  • If you need additional parameters from the original JSP you can pass them as liferay-util:param tags inside the liferay-util:include tag.
  • Request or Session attributes are still available, so you can get attributes using request.getAttribute() and so on.
  • As the second JSP now runs in the hook context classloader, you no longer have access to classes from portal-impl.jar

Happing coding!

 

 

Blogs