Using the serveResource() method for serving static Content

If you take a look at the implementation of serveResource() method in the GenericPortlet.java class you will notice that it is implemented like this


public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
if (request.getResourceID() != null) {
PortletRequestDispatcher rd = getPortletConfig().getPortletContext().getRequestDispatcher(
request.getResourceID());
if (rd != null)
rd.forward(request, response);
}
}


As you can see the default implementation reads the request.getResourceID() and forwards requests to that URL for generating response.

So lets say if i have a sampleimg.gif in my portlet .war file then i can include it in JSP either using the encodeURL method or using the serveResource() method like this

<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" session="false"%>
<%@taglib uri="http://java.sun.com/portlet" prefix="portlet"%>
<%@taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.1/portlet-client-model" prefix="portlet-client-model"%>
<%@taglib uri="http://java.sun.com/portlet" prefix="portletx"%>

<portlet:defineObjects />


<%
javax.portlet.ResourceURL url = renderResponse.createResourceURL();
url.setResourceID("/sampleimg.gif");
%>

<img src='<%= url.toString() %>' />


If you take a look at the HTML generated by this


/wps/myportal/!ut/p/c5/hZC7DoJAEEW_xcJSZ9ThYbkShVUUWeMDG7MhK24CYkTx9wVtbJA75ZmT3Fw4QnVXWepEPnR-lSkc4GiedjvuLxfuAG2aMeSOycRkGg4QseKReXJc5pHlI9rcIeQ0CcRwGqA7N2u7iQpqsanF3tdtGz-Qj74cG8Lwr_9p_5cTrLw8UxBBZP1sZMzGyDdEcxEaI3SHsL-rIn_eYwWii4XMbqnSWdJP9BnCWMYX5atSpWuZKLhl2wNq3rNfrPMG5V2x7Q!!/


As you can see the resourceID is encoded in the URL and this URL is pointing to the portal engine so it will enter through portal engine and then control will be forwarded to the sampleimg.gif. Using the serveResource() for including static content is not a good idea because it will require more processing power than including a normal file serving.

2 comments:

Anonymous said...

Hi,

You haven't created resourceURL anywhere in doView() or serveResource() in the portlet.

So how does Ajax know to call the serveResource() method of ValidationCacheSamplePortlet by using below line?

xmlHttp.open("GET","",true);

Abhi said...

Thanks for info....
SEO Company in Bangalore