Including JavaScript file in the Head of the page from portlet

One of the common requirement for portlet developer is how do i include a JavaScript file in the Head section of portal response page. I used the concept of Two phase rendering to build a sample portlet that includes JavaScript file in the head of the portal response.

This is how my TwoPhaseRenderPortlet.java looks like

package com.ibm.webspherenotes.jsr286;

import java.io.IOException;

import javax.portlet.GenericPortlet;
import javax.portlet.MimeResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import org.w3c.dom.Element;

public class TwoPhaseRenderingPortlet extends GenericPortlet{
protected void doHeaders(RenderRequest request, RenderResponse response) {
System.out.println("Entering TwoPhaseRenderingPortlet.doHeaders()");
Element script = response.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", request.getContextPath()+"/js/test.js");
response.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, script);

System.out.println("Exiting TwoPhaseRenderingPortlet.doHeaders()");
}
protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
System.out.println("Entering TwoPhaseRenderingPortlet.doView()");
response.setContentType("text/html");
response.getWriter().println("Hello from two phase rendering portlet");
System.out.println("Exiting TwoPhaseRenderingPortlet.doView()");
}
}


In the doHeaders() method i am creating a script element and setting its src attribute to point to test.js which is part of the portlet web application.
This approach is same as that i used for changing portal page title

When i access the page with the portlet, i can see the test.js being called, i kept this invalid URL so that its easier to see in firebug

4 comments:

Lou said...

what's the version of WPS you used in your example? Did you have to add the runtime option in the portlet.xml? Thanks for the info.

Pawinder said...

How do you achieve the same functionality in WPS 6.1.5

Abhi said...

Thanks for info
Web Design Company in Bangalore
Website development in Bangalore

Abhi said...

Thanks for info
Web Design Company in Bangalore
Website development in Bangalore