Home » Devtech review » LangsNTechs » Java » Liferay » 6 EE SP1 » Liferay 6 (5): get portlet content programmatically in hooked JSPs

Liferay 6 (5): get portlet content programmatically in hooked JSPs

Sometimes it is necessary to obtain a content of the portlet programmatically in hooked JSPs, but the APIs do not make it clear at all how to accomplish that.

There are some suggestions on the web on how this can be achieved, but the code seems to be somewhat complex, which makes it a problem to use in hooked JSPs.

For hooks there is a simpler method, but it relies on being executed in hooked JSPs by referring to some classes in portal-impl.jar:

Here it is – one method that could be put into JSP in order to obtain portlet content as a String variable value:

String getPortletContent(String portletName, RenderRequest renderRequest, RenderResponse renderResponse, PortletConfig portletConfig) {
	String result = "";
	try {
		HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest);
		StringServletResponse response = new StringServletResponse(PortalUtil.getHttpServletResponse(renderResponse));

		ServletContext servletContext = request.getSession(true).getServletContext();
		ServletContext rootWebappContext = servletContext.getContext("/"); // Should always be same as servletContext in hooked JSPs, but may be needed in future if the code would be somehow reused elsewhere

		RuntimeTag.doTag(portletName, null, rootWebappContext, request, response);

		PortletRequestImpl liferayPortletRequestImpl = (PortletRequestImpl)renderRequest;
		PortletResponseImpl liferayPortletResponseImpl = (PortletResponseImpl)renderResponse;

		liferayPortletRequestImpl.defineObjects(portletConfig, liferayPortletResponseImpl);
		result = response.getString();
	} catch (Exception e) {
	    _log.error(e);
	}
	return result;
}

This method is working in Liferay 6, but I would also expect it to work in Liferay 5.2.3 and latter, though I haven’t checked it myself. Still if it doesn’t I suspect that only a couple of modifications may be needed to get it working.

That’s all for now. Hope this was helpful.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s