Featured post

Docker setup for Liferay 7 with MySQL

Monday 24 October 2016

3 ways to use serve resource in portal

JSR-286 introduced resource serving and the same method can perform AJAX requests as well.
It's a  long time but I am just describing here with code snippets all you can do with resource method.

This example works with Liferay 7.

There are three ways you can use resource method from your portlet.
We will be looking at these with code snippets
  • You can download a file
  • You can fetch piece of data
  • You can return a jsp/ftl...

1) Download File

Create a hyperlink and create resource url(Same step needs to be done for all calls)

<portlet:resourceURL var="downloadURL" />

<a href="<%=downloadURL%>">Download Users</a>

Method in your portlet class

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
   throws IOException, PortletException {
   resourceResponse.setContentType("text/csv");
   resourceResponse.addProperty(HttpHeaders.CONTENT_DISPOSITION,
      "attachment;filename=sample.csv");
   OutputStream out = resourceResponse.getPortletOutputStream();
   String names = "Vipin , Bardia";
   
   InputStream in = new ByteArrayInputStream(names.getBytes());
   IOUtils.copy(in, out);
   
   out.flush();
}



2) Fetch dynamic data

Javascript call

jQuery(".htmlButton").click(function() {
      jQuery.ajax({
          url:$("#resource_url").val(),
          success: function(data)
          {
              jQuery('#result').html(data);
          }
  });
 });

Method in your portlet class


public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
   throws IOException, PortletException {
        resourceResponse.getWriter().write("I am sending my name : Vipin Bardia");
}

3) Return the jsp in AJAX call

Javascript call

Same javascript call as we used in example 2 to fetch dynamic data.


Method in your portlet class

public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
   throws IOException, PortletException {
        include("/MYAJAX.jsp", resourceRequest, resourceResponse);
}

You are just done, Try & Enjoy the function.............:)

No comments:

Post a Comment