Developing Ajax Portlets with Eclipse WTP

0.00 avg. rating (0% score) - 0 votes

JSR 168 Portlet APIs and portlet request processing model is not suitable for Ajax. It is not possible to make asynchronous calls to portlets through portlet URLs. Portlet URLs enable window state and mode changes that require a subsequent render request to the portal or portlet container. As a result, the response contains more than what we would like for Ajax, a response for the portal, including all the other rendered portlets. You can find a nice discussion of these issues at Best Practices for Applying Ajax to JSR 168 Portlets by By Greg Ziebold and Marina Sum.

Inspired by Ziebold and Sums article, my favorite Ajax toolkit jQuery, and the need for good examples for developing portlets using the Vignette Application Portal I used the jQuery File Tree example in a JSR 168 portlet.  This portlet is  a file explorer that lets you browse the file and folders on a server. This Ajax Portlet uses JQuery on the client side to request contents of the selected folder, and JAX-RS/REST style services on the server  sends back responses.

VAP Setup

To do develop VAP portlets with with Eclipse, we will setup an environment. You can follow the instructions at Using Eclipse WTP for Development with Vignette Application Portal . I tried the example code on other portals such as Pluto and Liferay so you can definitely use it on other portals.

The Architecture

A portlet is a Web application: In addition to the portlet and portlet related JSPs, it can contain other servlets, JSP pages, web services, REST services etc. We can make the asynchronous requests to the servlets and services that are bundled in the same Web application as the portlet. For example, when the user clicks on a folder, the client will send an asynchronous request to server to as for the contents of this folder and render it on the client.


A Portlet Project is a Dynamic Web Project

A portlet is a Web application, and like any other Web application it is developed using a Dynamic Web Project. Assuming you have already setup a Vignette Portal as your server, create a new Dynamic Web Project and name it FileExplorerPortlet.  Target the Web application to your server.  This project will have the normal src folder Java code, and WebContent folder for the rest of the Web resources.  Next we must add JSR 168 API (the classes that are in the javax.portlet.* packages), portlet tag libraries, etc. to the classpath.  Typically, every portal provides these in a set of jars.  You must find whet they are, create a user library and add them to your project.  For VAP 7.4.2, these libraries can be found at $VAP_HOME/lib/shared:

  1. $VAP_HOME/Portal/lib/shared/ccpp-1_0.jar
  2. $VAP_HOME/lib/shared/portlet_20.jar
  3. $VAP_HOME/lib/shared/vgnhpdapi-7.0.jar
  4. $VAP_HOME/lib/shared/vgnhpdapi-7.1.jar
  5. $VAP_HOME/lib/shared/vgn-jsr-container-shared.jar
  6. $VAP_HOME/lib/shared/vgn-jsr-container-taglib.jar
  7. $VAP_HOME/lib/shared/vgnportalclasspath.jar
  8. $VAP_HOME/lib/shared/vgn-portal-config.jar
  9. $VAP_HOME/lib/shared/vgn-portal-log-spi.jar
  10. $VAP_HOME/lib/shared/vgn-portal-naming-portlet.jar
  11. $VAP_HOME/lib/shared/vgn-portal-shared.jar
  12. $VAP_HOME/lib/shared/vgn-portlet-app-registry.jar
  13. $VAP_HOME/lib/shared/vgn-upm-api.jar

Add the User Library to the Dynamic Project. Open the project properties dialog, click on the Java Build Path and select the Library Tab.  Click on the add “Add Library…”, choose User library and define a new one named “VIG-SHARED” that contains all the jar files listed above.  Click Finish then OK to close the project properties dialog.  We now have a project ready to write our code.


Add a new Portlet

To start, we will add a standard JSR 168 portlet, portlet web resources and portlet deployment file to render our application in a portal:

  1. Create a new portlet class.
  2. Add the view and edit JSP files.
  3. Add jQuery JavaScript library, css and image files.
  4. Edit the view.jsp to develop the client side code to implement the File Explorer.
  5. Add the portlet.xml.

Create a new Portlet Class

Add the following class named FileExplorerPortlet to the com.eteration.portlet.samples package.

public class FileExplorerPortlet extends GenericPortlet {

private static final String viewPage = "/WEB-INF/jsp/view.jsp";
private static final String editPage = "/WEB-INF/jsp/edit.jsp";
private static final String session_directoryPath = "com.eteration.portlet.samples.directoryPath";
private static final String explorer_pref = "fileExplorerPref";

protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {

if (getPortletContext().getResourceAsStream(viewPage) != null) {
try {
// dispatch view request to view.jsp
PortletRequestDispatcher dispatcher = getPortletContext()
dispatcher.include(request, response);
} catch (IOException e) {
throw new PortletException(
"FileExplorerPortlet.doView exception", e);
} else {
throw new PortletException("view.jsp missing.");


protected void doEdit(RenderRequest request, RenderResponse response)
throws PortletException, IOException {

if (getPortletContext().getResourceAsStream(editPage) != null) {
try {
// dispatch edit request to edit.jsp
PortletRequestDispatcher dispatcher = getPortletContext()
dispatcher.include(request, response);
} catch (IOException e) {
throw new PortletException(
"FileExplorerPortlet.doEdit exception", e);
} else {
throw new PortletException("edit.jsp missing.");


public void render(RenderRequest request, RenderResponse response)
throws PortletException, IOException {

// set response content-type to value in request

// if set, get invoice from preferences, else null
String prefDirectory = request.getPreferences().getValue(explorer_pref,

// if set, get current directory path from session, else null
String sessionDirectory = (String) request.getPortletSession()

if (sessionDirectory == null && prefDirectory != null) {
// if new session and pref is set, put pref in session
prefDirectory, PortletSession.APPLICATION_SCOPE);

super.render(request, response);


// Portlet Edit Action (edit.jsp)
public void processAction(ActionRequest request, ActionResponse response)
throws PortletException, IOException {

String directory = request.getParameter(explorer_pref);
if (directory != null) {
PortletPreferences prefs = request.getPreferences();
prefs.setValue(explorer_pref, directory);;

// set new preference in session
directory, PortletSession.APPLICATION_SCOPE);



Add the view and edit JSP files.

Our portlet supports the view and edit modes. I like using the JSTL tags (JSP Standardized Tag Library), so I have downloaded the corresponding jars and added them into my WEB-INF/lib folder. The presentation layer for these modes will be coded in the corresponding JSP files. We start with adding the edit.jsp using a standard portlet page template that looks like the following:

<%@ taglib uri="" prefix="portlet" %>
<%@ taglib uri="" prefix="c" %>
<%@ page import="javax.portlet.PortletSession" %>
<%@ page session="false" %>
	// check for selectedDirectory in session
	String selectedDirectory = (String)renderRequest.getPortletSession().getAttribute(
	if ( selectedDirectory != null ) {
		pageContext.setAttribute("selectedDirectory", selectedDirectory);
		selectedDirectory = "/";

<form target="_self" method="POST" action="<portlet:actionURL portletMode="view"/>">
<b>Default Directory:</b>
<input type="text" name="directoryPref" value="<%= selectedDirectory %>">
<input type="submit" value="OK"/>

When this form is submitted to the portlet:actionURL, it will be processed by the public void processAction(ActionRequest request, ActionResponse response) in the portlet code. Next we will add the view.jsp, which the main UI for the FileExplorerPortlet. view.jsp has the standard portlet JSP tags and the place holder divs for the JQuery code.

<%@ taglib uri="" prefix="portlet" %>
<%@ taglib uri="" prefix="c" %>
<%@ page import="javax.portlet.PortletSession" %>
<%@ page session="false" %>

	// check for selectedDirectory in session
	String selectedDirectory = (String)renderRequest.getPortletSession().getAttribute(
	if ( selectedDirectory != null ) {
		pageContext.setAttribute("selectedDirectory", selectedDirectory);
		selectedDirectory = "/";

<div id="<portlet:namespace/>_main">

<div class="fileExplorerC">
	<h2>File Explorer</h2>
	<div id="fileExplorer" class="demo"></div>

<div id="<portlet:namespace/>_content"></div>

jQuery JavaScript library, css and image files

JQuery as advertised on their web site “is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development”. To use JQuery in our portlet, we need to include the corresponding .js files. We will include three js files: 1) the JQuery library jquery.js. 2) FileTree jqueryFileTree.js. and 3) The animation for the folders jquery.easing.js. We will do this by adding the following code into the view.jsp file right after the <div id=”_main”> tag. The code looks a little complicated but it is there too avoid reloading the jquery libraries if they are already loaded.

<script src="<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/js/jquery.js") %>"  type="text/javascript" ></script>
<script src="<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/js/jquery.easing.js") %>"  type="text/javascript" ></script>
<script src="<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/js/jqueryFileTree.js") %>"  type="text/javascript" ></script>

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

The File Explorer

To write the file explorer add the following jQuery script right below the previous one. This code starts the root of the file explorer at the selectedDirectory, and every time we click on a folder, it sends an Ajax request to our servlet to get the contents of the folder. It will then replace the contents of the div with the “fileExplorer” id.

<script type="text/javascript">
$(document).ready( function() {
	 root: '<%= selectedDirectory%>',
	 script: '<%=renderResponse.encodeURL(renderRequest.getContextPath() + "/FileExplorerServlet")%>',
	 folderEvent: 'click',
	 expandSpeed: 750,
	 collapseSpeed: 750, multiFolder: false },
	 function(file) {


We will finish the portlet development by adding the portlet deployment configuration file, the portlet.xml, into the WEB-INF folder. Our portlet only has the edit and view modes. Also we have a portlet preference for the root directory path of the FileExplorer.

<?xml version="1.0" encoding="UTF-8"?>
<portlet-app xmlns=""
	xmlns:xsi="" xmlns:portlet=""

Add the new Servlet for processing the Ajax Requests

In our portlet, when the user click on a directory, JQuery sends an Ajax request to the Web application. This request bypasses the portal and is directly handled by a servlet. This way the response is not processed by the portal and is directly available to the client. This architecture allows us to develop with standard JavaEE Servlet/JSP coding. Any parameters and/or attributes we would like to share with the potlet is passed via the HttpSession or HttpServletRequests. To do this we will:

  1. Create a new servlet class.
  2. Add a JSP file to generate the directory contents

Add a new Servlet

Add a new Servlet class named the FileExplorerServlet into the package com.eteration.servlet.samples. Make sure the code looks like the following:

package com.eteration.servlet.samples;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FileExplorerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public FileExplorerServlet() {

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// String dir = request.getParameter("dir");
		// System.out.println("Dir:" + dir);
		this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/jqueryFileTree.jsp").forward(request, response);

The servlet forward the request to JSP  to do all the processing.  For this implementation, the Servlet seems redundant.  It is here for demonstrating the use of a Servlet with a Portlet.


To create the directory response, we will have to create a html fragment that includes the contents of the folder. jQueryFileTree component requires an unordered list with folders and files as list items.

<ul class="jqueryFileTree" style="display: none;>
  <li class="directory collapsed"><a href="#" rel="/myfolder" >foldername</a></li>
  <li class="file ext_pdf"><a href="#" rel="/myfolder/myDoc.pdf" >My PDF Document</a></li>

Add the following JSP (it is provided as an example with the jQueryFileTree component) jqueryFileTree.jsp to generate these fragments for a given folder. Make sure the code looks like the following:

<%@ page
  * jQuery File Tree JSP Connector
  * Version 1.0
  * Copyright 2008 Joshua Gould
  * 21 April 2008
    String dir = request.getParameter("dir");
    if (dir == null) {

	if (dir.charAt(dir.length()-1) == '\') {
    	dir = dir.substring(0, dir.length()-1) + "/";
	} else if (dir.charAt(dir.length()-1) != '/') {
	    dir += "/";
    if (new File(dir).exists()) {
		String[] files = new File(dir).list(new FilenameFilter() {
		    public boolean accept(File dir, String name) {
				return name.charAt(0) != '.';
		Arrays.sort(files, String.CASE_INSENSITIVE_ORDER);
		out.print("<ul class="jqueryFileTree" style="display: none;">");
		// All dirs
		for (String file : files) {
		    if (new File(dir, file).isDirectory()) {
				out.print("<li class="directory collapsed"><a href="#" rel="" + dir + file + "/">"
					+ file + "</a></li>");
		// All files
		for (String file : files) {
		    if (!new File(dir, file).isDirectory()) {
				int dotIndex = file.lastIndexOf('.');
				String ext = dotIndex > 0 ? file.substring(dotIndex + 1) : "";
				out.print("<li class="file ext_" + ext + ""><a href="#" rel="" + dir + file + "">"
					+ file + "</a></li>");

The web.xml

The servlet deployment descriptor web.xml is the standard web xml, and will read as the following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns=""
	xmlns:xsi="" id="WebApp_ID"
		<description />

This is it for the coding. We are now ready to deploy and test it using our portal.

Deploying a JSR 168 Portlet to VAP

A JSR 168 Portlet is packaged as a standard Web Application Archive (WAR) file. It is deployed to an application server using the same techniques as any other Web application. When developing with eclipse, we would add the dynamic web project to Server as any other Web application.


There is only one Vignette specific step before we can deploy this WAR file. Vignette requires that a JSR 168 war file is pre-processed by the “PortletPackageTool”. This tools adds Vignette specific, servlets, filters and listeners. The packaging tool is an Ant task that adds the information required by Portal
to a portlet application’s web.xml file Then , we use the processed WAR file for deployment. The packaging tool scripts and examples are provided with the VAP distribution ($VAP_HOME/ant/bin). When using eclipse we can simplify this step by creating an ant build.xml file and run it once. This will add all the necessary code into the web.xml. When the Portlet application is started, the Portlet appears in the Portal administration consoles. The Portal Portlet Packaging Tool needs to be run only once; if the portlet application is modified and redeployed, the tool does not need to be re-run because the entries in the web.xml does not change.

<?xml version="1.0" encoding="UTF-8"?>

<project name="repackage_portlets" default="run" basedir=".">

	<property name="VAP_HOME" value="/home/ndai/dev/vignettehome/Vignette/Portal" />
	<path id="vignette.ant.classpath">
		<fileset dir="${VAP_HOME}/ant/lib_portal">
			<include name="**/*.jar" />
	<taskdef name="PortletPackageTool" classname="com.vignette.portal.ant.external.portlet.PackageTask" classpathref="vignette.ant.classpath" />

	<target name="run">
		<record name="portlet_package_log.txt" loglevel="info" />
		<PortletPackageTool destdir="${basedir}" dir="${basedir}/WebContent" contextroot="FileExplorerPortlet" rename="true" failonerror="false">


Enabling Direct Requests to a Portlet Application

The Portal Portlet Packaging Tool adds a security filter to a portlet application’s web.xml file. This filter allows direct requests to static files, such as images, but it blocks all requests to servlets and JSPs that are not proxied through Portal, thereby ensuring that the Portal authentication and authorization mechanisms protect all application resources. As a result, a Portal user is forbidden to access a portlet application directly. Hwoever, we need to make direct requests to the FileExplorerServlet. To enable access we will remove the Portal security filter (named PortletApplicationSecurityFilter) and the mapping. Delete or comment the following lines:


Once you complete the deployment, start the VAP server. Login to the Server console (http://localhost:8080/portal/console). JSR 168 portlets are listed under Portal Application. Create a new FileExplorer portlet and add it to a page. You can now test/debug your portlet.



Naci Dai is the chief scientist and founder of eteration, a.s. An active open source advocate, he created the ObjectWeb Lomboz project and is a member of the Eclipse Web Tools Platform project. Naci is a member of the faculty at Sabanci University, where he teaches object technologies and distributed computing. He received a Ph.D. from Carleton University.

Tagged with:
Posted in Blog
3 Comments » for Developing Ajax Portlets with Eclipse WTP
  1. Betül says:

    Thanks for the blog, it works 🙂 but after a long struggle 🙂

    There is one thing to pay attention: Do not add vap jars to module dependencies. If you do, your portlet will not be viewed in the portal.

  2. How we can get a copy of vignette tool for development (free version for development)?

    • Naci says:

      Vignette is now called OpenText and you probably have to contact their website to findout how to get a copy. I would recommend an open source portal (such as apache pluto or liferay) if you are just trying things. They are easy to learn and download.

2 Pings/Trackbacks for "Developing Ajax Portlets with Eclipse WTP"
  1. […] be wasted if we cannot do the all familiar eclipse style development. So, here comes the fun part. Developing an Ajax Portlet VN:F [1.6.5_908]please wait…Rating: 0.0/5 (0 votes cast)VN:F [1.6.5_908]Rating: 0 (from 0 […]

  2. […] can see a tutorial about creating portlet class and adding portlet.xml file. We will concentrate to adding view jsp and adding servlet for ajax […]

Leave a Reply

Your email address will not be published. Required fields are marked *


Time limit is exhausted. Please reload the CAPTCHA.