Including static content in your Portlet

I wonder if I'm the only one who didn't know how to include and reference static content from a portlet. Recently when writing a portlet I was clueless on what to do when I wanted to include images and a CSS file in my portlet. I figure there might be someone out there who doesn't remember this stuff as well; or may be not. But I'll go ahead and post the technique here anyway.

To include static content in your portlet, just put your files (e.g., images, Javascript files, CSS files) under the portlet web-application root. To reference them in your portlet use the renderRequest.getContextPath() method. For example, you can include a CSS file like this

<link rel="stylesheet" type="text/css" href="<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/style.css")%>"/>

renderRequest.getContextPath() returns the web-application path of the Portlet. So for a portlet MyPortlet deployed on your localhost, the method will return http://localhost:80/MyPortlet. Note: Remember to include the following declarations in your page before using the renderResponse object.

<%@ page import="javax.portlet.*"%>
<%@ taglib uri="http://java.sun.com/portlet" prefix="portlet" %>
<portlet:defineObjects/>


Changing Title of a Portlet

This is quite easy. Just do the following: renderResponse.setTitle("Portlet Title");