Liferay:Developing a Portlet with Multiple Actions

Developing a Portlet with Multiple Actions

So far we have developed a portlet that has two different views, the default view and an edit view. Adding more views is easy and all you have to do to link to them is to use the mvcPath parameter when creating the URL. But we only have one action. How do we add another action, for example for sending an email to the user?

You can have as many actions as you want in a portlet, each of them needs to be implemented as a method that receives two parameters – an ActionRequest and an ActionResponse. The name of the method can be whatever you want since you will be referring to it when creating the URL.

Let’s rewrite the example from the previous section to use a custom name for the action method that sets the greeting and add a second action method for sending emails.

public class MyGreetingPortlet extends MVCPortlet {
    public void setGreeting(
         ActionRequest actionRequest, ActionResponse actionResponse)
    throws IOException, PortletException {
       PortletPreferences prefs = actionRequest.getPreferences();
       String greeting = actionRequest.getParameter("greeting");

       if (greeting != null) {
         try {
          prefs.setValue("greeting", greeting);
          prefs.store();
          SessionMessages.add(actionRequest, "success");
         }
         catch(Exception e) {
          SessionErrors.add(actionRequest, "error");
         }
       }
    }

    public void sendEmail(
         ActionRequest actionRequest, ActionResponse actionResponse)
    throws IOException, PortletException {
       // Add code here to send an email
    }
}

Note how we no longer need to invoke the processAction method of the super class, because we are not overriding it.

This change of name also requires a simple change in the URL, to specify the name of the method that should be invoked to execute the action. In the edit.jsp modify the actionURL so that it looks like this:

<portlet:actionURL var="editGreetingURL" name="setGreeting">
    <portlet:param name="mvcPath" value="/edit.jsp" />
</portlet:actionURL>

That’s it; now you know all the basics of portlets and are ready to use your Java knowledge to build portlets that get integrated in Liferay. The next section explains an extension to the portlet specification that Liferay provides to generate pretty URLs to your portlets.


你可能感兴趣的:(exception,action,Parameters,email,extension,portlet)