Monday, August 23, 2010

Serving resource using JSR 286

In JSR 286, one more method is getting introduced in portlet life cycle that is serveResource, the advantage of this method is, we can get resource in portlet response which is not possible in JSR 168.

Let's take an example for better understanding the use of serveResource method. Suppose, you have a collection of images and you need to display different images according to the selection. What you will do is?
First, you need to create a resource URL as mentioned below,

ResourceURL resourceURL = renderResponse.createResourceURL();

Now, you need to make a hiperlink through which you call the serveResource method. The code for reference is,
<a href="<%=resourceURL.toString() %>">Resource</a>

When you click on this link, it makes an Ajax call using resourceURL and call the serveResource method. Once it is called you can set the response for images (which is not effected in JSR 168) and write this byte format of image in XML format. Now response is ready which is called using Ajax callback methods. The reference code lines are,

public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {   
 response.setContentType("image/jpeg");
 // Image in byte stream
 byte[] b = getImage(); //Returns image bytes
 // writing image byte stream on portlet response
 response.getPortletOutputStream().write(b);
}

Also, you can use different types of resources. What you need to do is?
you have to add the following code with resourceURL,
resourceURL.setResourceID("image");

Through this ID you can perform your logic according to the image resource ID. You can get Id in serveResource method using code below,

request.getResourceID().

2 comments:

Prakash said...

Hi dileep, do we need to write any extra piece of code to make the resourceURL call asynchronous(Ajax) or resourceURL itself makes a ajax call.

dilip gupta said...

Sorry for late response..
This feature is introduced in JSR-286 specification which is called when you make request for resource URL (GenericPortlet contains separate method as doView() or doEdit()) and you do not require AJAX call to implement this.