Using the serveResource() method for serving static Content

If you take a look at the implementation of serveResource() method in the 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(
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="" prefix="portlet"%>
<%@taglib uri="" prefix="portlet-client-model"%>
<%@taglib uri="" prefix="portletx"%>

<portlet:defineObjects />

javax.portlet.ResourceURL url = renderResponse.createResourceURL();

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

If you take a look at the HTML generated by this


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.

1 comment:

Anonymous said...


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?"GET","",true);