Thursday, June 12, 2014

Creating liferay portlet - how to pass data to view.jsp from Java class?

Q: I'm trying to create portlet in liferay with just only from a JSP file called view.jsp. What I need is:

  1. When the portlet loads, I want to call custom Java class where I generate an array.
  2. I need to pass that array to the view.jsp.
How to do that?

Answer: Have you created your portlet with the create.sh script from Liferay? In this case, we will need to create a new portlet class that extends MVCPortlet:
public class ArrayPortlet extends MVCPortlet {

}
Also, you will have to change the WEB-INF/portlet.xml file to point to its class. Replace the line below by
<portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</portlet-class>
by one naming your portlet class:
<portlet-class>br.com.seatecnologia.arrayportlet.ArrayPortlet</portlet-class>
This is just setup. Now, the cool part: code! You should create a method for handling the view of the portlet. This method should be named doView() and has two parameters: a RenderRequest and a RendertResponse. Also, it throws some exceptions and delegate the portlet rendering to the superclass method:
public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
    super.doView(renderRequest, renderResponse);
}
Before rendering the portlet, however, we create our array:
String[] array = new String[] { "foo", "bar", "baz" };
and put it in the RenderRequest received as parameter. You should give a name to the parameter - in this case, the name is "my-array":
renderRequest.setAttribute("my-array", array);
This is our class, complete:
public class ArrayPortlet extends MVCPortlet {
    @Override
    public void doView(RenderRequest renderRequest, RenderResponse renderResponse)
    throws IOException, PortletException {
        String[] array = new String[] { "foo", "bar", "baz" };
        renderRequest.setAttribute("my-array", array);
        super.doView(renderRequest, renderResponse);
    }
}
It is through the RenderRequest object that we pass values to the JSP. Now, in the JSP, we should "import" the RenderRequest instance (and other objects as well) adding the <portlet:defineObjects /> tag to the beginning of the JSP. After this, we can get any attribute from the renderRequest object through its name. Note that the method getAttribute() returns Object so you should cast its return value to the correct type:
<portlet:defineObjects />
<%
String[] anArrayFromMyPortlet = (String[])renderRequest.getAttribute("my-array");
%>
Now, you just use your retrieved object as you wish:
<ul>
<% for (String string : anArrayFromMyPortlet) { %>
<li><%= string %></li>
<% } %>
</ul>

No comments:

Post a Comment