Skip to content

How to Use Resource Command for Ajax in Liferay 7?

Featured Image

Asynchronous JavaScript and XML, popularly known as Ajax is used with Liferay technology to update portlet content or small portion of the whole page. Eventually, while creating Liferay’s MVC framework, the resource URLs can be created in the JSPs for retrieving messages, XML or even any other kind of resource from the Liferay instance. This resource URL further invokes corresponding MVC resource command class (*MVCResourceCommand) that ultimately processes the resource request and response.

Resource Command for Ajax in Liferay 7

The resource command for Ajax calling in Liferay MVC framework is built for retrieving data as a response from the server. For this, a separate class is created as Resource Command class for handling Ajax calls. Previously in Liferay 6 Handler method was used to handle Ajax in the portlet controller.

Example of Resource URL in JSP:

<portlet:resourceURL id=”getUserDocuments” var=”getUserDocumentsURL” />

When we hit resource URL from JavaScript or JSP, it will find corresponding MVCResourceCommand class. We can create our own class by implementing the MVCResourceCommand interface or extending the BaseMVCResourceCommand class.

Sample MVC Resource Command Class:

@Component( immediate = true, property = { ““Your_Portlet_ID”, ““getUserDocuments” }, service = MVCResourceCommand.class ) public class UserDocumentModulePortlet implements MVCResourceCommand { @Override public boolean serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws PortletException { // Write your logic here. } }

One has to define @Component annotation and value that will be the respective portletId. The portletId can be found by the controller class package and controller class name.

For example, if the Controller class have package as com.example.learn.portlet and controller class name as “UserDocumentModulePortlet”, then the portletId will be com_example_learn_portlet. UserDocumentModulePortlet.

Here, must match with the id attribute in <portlet:resourceURL>.

This is how Ajax call in Liferay 7 is done.

Still in case of any queries, feel free to contact our Liferay Consultant!

Related Insights