Q: I'm trying to create portlet in liferay with just only from a JSP file called
Answer: Have you created your portlet with the
view.jsp
. What I need is:- When the portlet loads, I want to call custom Java class where I generate an array.
- I need to pass that array to the
view.jsp
.
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
:Also, you will have to change thepublic class ArrayPortlet extends MVCPortlet { }
WEB-INF/portlet.xml
file to point to its class. Replace the line below byby one naming your portlet class:<portlet-class>com.liferay.util.bridges.mvc.MVCPortlet</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<portlet-class>br.com.seatecnologia.arrayportlet.ArrayPortlet</portlet-class>
doView()
and has two parameters: a RenderRequest
and a RendertResponse
. Also, it throws some exceptions and delegate the portlet rendering to the superclass method:Before rendering the portlet, however, we create our array:public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { super.doView(renderRequest, renderResponse); }
and put it in theString[] array = new String[] { "foo", "bar", "baz" };
RenderRequest
received as parameter. You should give a name to the parameter - in this case, the name is "my-array"
:This is our class, complete:renderRequest.setAttribute("my-array", array);
It is through thepublic 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); } }
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:Now, you just use your retrieved object as you wish:<portlet:defineObjects /> <% String[] anArrayFromMyPortlet = (String[])renderRequest.getAttribute("my-array"); %>
<ul> <% for (String string : anArrayFromMyPortlet) { %> <li><%= string %></li> <% } %> </ul>
No comments:
Post a Comment