Embedding Groovy in a JSR 168 portlet for total scripting power

Bring your portlets to life with Groovy


Imagine you are surrounded by gobs of demanding managers barking impossible orders with timelines that only fools or heroes wouldn’t scoff at. You raise your head to the heavens and laugh in the face of adversity because you know that you have just the tool to win the day. It is a tool for speed and flexibility, which, when used properly, enhances your ability to overcome impossible demands. And, it just might help you win the day for an important POC or demo you might have on the horizon.

Reflecting on a recent portlet building experience that took about an hour to code and test on our server made us wonder how we could possibly speed up this process. Suppose you need to build a simple, "bread-and-butter" portlet that connects to a database, gets some data based on request parameters, formats the data, and sends it back to the client. Nothing fancy. We know from dabbling with Project Zero that the obvious answer to speeding up this task is to script it.

So follow along as we guide you through creating a portlet using a Rational Software Architect Version 7.0 wizard to embed Groovy functionality into generated code and testing it on-the-fly (dynamically) in the various portlet modes. That is, you see a completely scripted portlet. Far out and groovy!

Did you say Groovy?

Yes, Groovy! If you have not heard of Groovy yet, then obviously you’ve spent far too much time up to your elbows riding a world of chaos. Groovy is a very powerful agile and dynamic language. It is a superset of Java, and it can run in an interpreted mode inside the JVM enabling seamless integration with all existing Java objects and libraries. Because it compiles straight to Java byte code, you can use it wherever you use Java which is one of the reasons why you will want to use this scripting language with your Java portlets.

For more information on Groovy, check out the Related topics section.

Why Groovy?

You might ask, "Why Groovy when there is Ruby, Python, Smalltalk, and so on"? Andrew Glover makes a simple, efficient observation about that very question in his article alt.lang.jre: Feeling Groovy (see Related topics). As he points out, the answer is easy syntax and reuse of standard Java libraries.

Even though Groovy is similar to Ruby in that they both have a bunch of really nice features such as closures, syntax for advanced data structures, inline strings and so on, Groovy is very tightly integrated into the Java platform. You can compile a Groovy script directly into a .class file that is just like any other class in Java. Likewise, you can reuse any Java class and library within Groovy.

Groovy is a superset of Java that can run in an interpreted mode inside the JVM. Ruby and other scripting languages require an external interpreter, which might cause a raft of security issues. Any time you need to "shell out" you introduce a potential for injection attacks.

Writing a Groovy based portlet

Before you begin your journey with the Rational wizard, consider how Groovy will help you in your efforts. You can easily embed Groovy scripts in Java programs by direct compilation. The Groovy compiler, groovyc, converts the Groovy code to byte code so that it is understandable by the JVM. When you compile a Groovy program, the compiler generates class files. You can insert the path for these files in the CLASSPATH environment variable, and then use them as objects in your Java program.

You can also integrate Groovy scripts easily in Java code using three classes: GroovyShell, GroovyClassLoader, or GroovyScriptEngine. Using the GroovyShell class, you can write Groovy expressions inline with Java programs. You can then evaluate these expressions using the temporary shell provided by the GroovyShell class. The GroovyClassLoader class loads the Groovy classes required by the Groovy script file to run in a Java program. The GroovyScriptEngine class embeds multiple Groovy scripts in Java programs and lets you reload and recompile the scripts if any modification occurs.

In this article, you see how to use the GroovyShell class to achieve your goal.

Enough with the small talk, Brave Hero. It is time for you to forge your tool so that you can hone your skill. To the wizard then!

Create a basic portlet using a Rational IDE wizard

If you are familiar with the Rational IDE wizard for creating a JSR168 portlet project and want to skip the details, create a basic portlet and proceed to the section Complete the Java code. For other folks who have preferred using command line editor tools for years, but have always been curious about the Rational IDE wizard, come, get a taste by reading on!

  1. In your chosen Rational IDE (Rational Software Architect or Rational Application Developer), select File => New => Project.
  2. Verify that the Show All Wizards checkbox is checked.
  3. Expand the Portal folder.
  4. Select Portlet Project (JSR 168).
  5. Click the Next button.
  6. If asked if you would like to enable the Portal Development capability, click OK.
  7. On the New Portlet Project page of the wizard, type the name of the project in the Name field: GroovyPortlet. The Rational IDE uses this name to create a directory for your portlet project.
  8. Make sure WebSphere Portal v6.0 is selected in the TargetRuntime field.
  9. De-select the Add project to an EAR option in EAR Membership.
  10. In the Portlet API drop-down select JSR 168 Portlet, and in the Portlet type field, select the Basic Portlet (JSR 168) portlet type. This option creates base Java code and JSPs for the portlet.
  11. Make sure that Create a portlet is selected and then click Next.
  12. If you would like to include tag libraries in your dynamically generated response, select Show advanced settings => JSP Standard Tag Library.
  13. On the Portlet Settings page, select the edit, help, and view modes. Enter a package prefix ( in this example) and click Next.
  14. On the Action and Preference page, de-select the Add action listener button, and then click Finish. The Rational IDE generates your starter project and code.
  15. If you are asked to change perspective to the Web perspective, click Yes.
  16. After the code is generated, your project should look similar to the following in the Project Explorer view.

Complete the Java code

  1. Include the following lines at the top of the portlet Java file, in this case, immediately after the declaration for the package, so that you can use Groovy methods and make calls to its shell:
    Listing 1. Get access to the groovy classes
    import groovy.lang.Binding;
    import groovy.lang.GroovyShell;
    import java.util.logging.Logger
  2. Next, declare a logger instance to create a logger for your GroovyPortlet by adding this line after the other declarations:
    Listing 2. Declare a logger
    public static final Logger logger = Logger.getLogger(GroovyPortlet.class.getName());
  3. In the doView() method, add code as shown in Listing 3 to embed Groovy expressions in Java code.
    Listing 3. Add a Groovy expression to your code
    public void doView(RenderRequest request, RenderResponse response) 
      throws PortletException, IOException {
      // Set the MIME type for the render response
      // Call groovy expressions from Java code
      Binding binding = new Binding();
      binding.setVariable("request", request);
      binding.setVariable("response", response);
      binding.setVariable("context", getPortletContext());
      binding.setVariable("logger", logger);
      binding.setVariable("test", new Integer(10));
      GroovyShell shell = new GroovyShell(binding);
      // Invoke the JSP to render
      PortletRequestDispatcher rd = getPortletContext().
        getRequestDispatcher(getJspFilePath (request, VIEW_JSP));
      PortletPreferences prefs = request.getPreferences();
      String code = prefs.getValue("code", 
        "response.getWriter().println('<p>No code has been " + 
        "set in portlet preferences</p>')"); 

    The GroovyShell class is contained in the groovy.lang.GroovyShell package; it provides a shell to perform Groovy scripts at run time. You use the GroovyShell class and Bindingobject to modify Groovy expressions in the Java environment. The Binding object lets you bind objects to a Groovy script so that they can be used as variables. For example, you bind the getPortletContext() method and expose it as context.

To run a Groovy script in a Java program, you first create an instance of the GroovyShell class. Then, use the binding (which you set earlier in the Java code), call the evaluate() method which processes the setting and returns the result.

In the doEdit() method, add the code in Listing 4 before the JSP include block. This code retrieves the name-value pair stored in portlet preferences and then stores the Groovy expressions entered in the edit mode of the portlet into the code parameter in the request attribute.

Listing 4. Fetch name-value pair from portlet preferences
PortletPreferences prefs = request.getPreferences();
String code = prefs.getValue("code", "");
request.setAttribute("code", code);

Finally, in the processAction() method, replace the contents with the snippet in Listing 5 to process the action request. This code first obtains the PortletPreferences object. When the user clicks the Submit button in the Edit mode, the code checks to see if any new data was added. If so, it retrieves the data through the getParameter() call and the new values are set into the Portlet Preferences object. The store() method of the preferences object stores the new values. The store() method invocation will fail if the values for code are invalid.

Listing 5. Process the action request
if( request.getParameter("newcode") != null ) {
  // Set a portlet preference
  String value = request.getParameter("code");
  if((null != value) && (!"".equals(value))) {
     PortletPreferences prefs = request.getPreferences();
     value = value.replaceAll("&lt;", "<");
     value = value.replaceAll("&gt;", ">");
     try {
        }catch( ReadOnlyException roe ) {

Complete the JSP code

Open GroovyPortletView.jsp that was generated by the wizard, and add a link as shown in Listing 6 to take the user to the edit mode. This form uses the renderURL tag from the portlet tag library. Portlets must use either the PortletURL actionURL or renderURL portlet tag to create links targeted to them because portlets are not bound to a URL; instead, they are invoked through the portal.

Listing 6. Add a renderURL portlet tag
<p align="right">
<a href="<portlet:renderURL portletMode="edit" />">edit</a>

To display something when users visit the page for the first time, add a few lines of HTML such as those shown in Listing 7.

Listing 7. Sample HTML lines
<DIV style="margin: 6px">

<H3 style="margin-bottom: 3px">Welcome to our test page!</H3>
You have to edit this page in order to see Groovy in action in a portlet. <BR>


Alternatively, if you would rather have your Groovy shell output rendered in the View JSP, transfer the output to the request object in the Java file (in this example, Then, collect and display it in GroovyPortletView.jsp.

In your Java file, collect the result in an Object and then transfer the output to the request object, as shown in Listing 8.

Listing 8. Collect result in an Object and transfer to request attribute
Object lastResult=shell.evaluate(code);
	if (lastResult!=null)
		request.setAttribute("result", lastResult);

Or, in your JSP, you could use code similar to that in Listing 9 to have your Groovy shell output rendered in the View JSP.

Listing 9. Output result to browser in View mode
<c:if test="${not empty requestScope.result}">
The result of evaluating your Groovy expression is <br /
> <c:out value="${requestScope.result}"/>

Next, in the GroovyPortletEdit.jsp, replace the existing code with the snippet shown in Listing 10. This code creates a simple form with a text area where you put your groovy expressions and code. The <portlet:actionURL>tag of the portlet tag library calls the processAction() method in the Java controller, calls the View mode where the Groovy expressions are executed within Java.

Listing 10. JSP code for Edit mode
<%@page session="false" contentType="text/html" pageEncoding="ISO-8859-1"
<%@taglib uri="" prefix="portlet" %>
<%@taglib uri=""  prefix="fmt" %>  
<%@taglib uri="" prefix="c" %>  
<%@ taglib uri="/WEB-INF/tld/ibm-portlet-ext.tld" prefix="portletExt" %>


Available vars:<br />


Enter your Groovy test code here :-<br />

<form action="<portlet:actionURL portletMode="view" />" method="post">
<textarea name="code" cols="40" rows="40"><c:out 
<br />
<input name="newcode" type="submit" value="submit" />

In this example, five variables are bound to the Shell object, and you can use them while writing your Groovy expressions.

request (RenderRequest): Defines methods to provide information regarding client requests to the portlet.
Example: request.getServerPort() returns the port of the server to which the client requests can be sent to access this portlet running on WebSphere Portal.

response (RenderResponse): Use this object to set the title of the portlet and generate content by either obtaining a writer or delegating to a JSP or Servlet.
Example: response.getWriter().println sends output to the client.

context (getPortletContext()): Obtains information from the server about the portlet or the entire Web application.
Example: context.getServerInfo() returns the information about the server software

logger (Logger.getLogger(GroovyPortlet.class.getName())) : The logger object called by the getLogger method that returns an appropriate logger.
Example: info_message) shows a log INFO message.

test (new Integer(10)): User defined variable of type Integer with a value of 10. So, you can create any variable you want and bind it to the Groovy Shell object. Then, at run time when you enter a Groovy expression to evaluate, you do not have to define that variable again; you can just enter something like test * 2 and the expression is evaluated.
Example: test * 2 returns a value of 20

Upon successful parsing, a script is returned which your shell will run.

Adding portlet and web descriptors

From ProjectExplorer, select GroovyPortlet => WebContent => WEB-INF, and then open portlet.xml. Later on, you will export this project as a WAR file to install and use in your WebSphere Portal environment. If you already have a WAR named GroovyPortlet installed on any server where you plan to use this portlet, you need to provide a unique id in the portlet-app tag.

Example: <portlet-app id="FinalTestGroovyPortlet">

Also, consider adding a description tag to uniquely identify each portlet that could be selected and added to a page). In step 9 of Deploying the portlet to a page, you will select a portlet from a list of portlets to add on to your test page. If you have a few portlets with the same name, such as GroovyPortlet, you need to add a description tag to uniquely identify your portlet from others.

Example: <description> FinalTestGroovyPortlet</description>

Import the Groovy classes and libraries

At this point, unless you have previously configured your Rational IDE to automatically build your project automatically, build it manually by following these steps:

  1. Select Project => BuildWorkingSet => GroovyPortlet.Tip: You can also choose to build your projects automatically in the same place.
  2. After the build is complete, verify that GroovyPortlet.class is created in your project folder. For this example, it is in: /GroovyPortlet/WebContent/WEB-INF/classes/com/ibm/tcat/spike

Building the project results in several errors similar to these:

You get these errors because you do not yet have the Groovy executable jar in your project.

To add the Groovy executable jar:

  1. Download Groovy 1.0 from the Groovy Web site at This sample project uses groovy-all-1.0.jar from the Groovy 1.0 version, but other newer versions might be compatible too.
  2. Extract the zip to your hard drive, for example, to C:\Groovy.
  3. From C:\Groovy\embeddable, copy groovy-all-1.0.jar file directly into the lib folder of your project.
  4. Right-click your project name, select Properties and then select JavaBuildPath.
  5. In the Libraries tab, you should see your copied JAR file inside of Web App Libraries. If you do not see it there, then delete Web App Libraries, and add it again to ensure that the JAR is there as the screenshot below shows.If your project builds automatically, you do not need to do anything. If not, you need to rebuild again by selecting Project => BuildWorkingSet => GroovyPortlet. Then you should see no more errors.

Tip: You can also import the JAR file directly into the project by clicking on the Add External JARs button in the Java Build Path. However, in this case, the JAR might not get copied in your WAR file; it will simply reference the JAR in your local system. The compilation in the Rational IDE will happen without any problems, but at run time you will see a noclassdef found error. So, to avoid this error, place the JAR directly in the lib directory of the project.

Now you need to export your project as a WAR file, install the WAR on a portal, and deploy it on a portal page for testing. The next few sections show you how to do these steps. If you are comfortable doing them on your own, do them and skip to the Test the portlet section.

Building the portlet

Compiling and packaging the portlet for deployment is a simple feat when you use the Rational environment. To review a basic portlet concept, portlets are packaged into Web Archive files, or WAR files, which are deployed into the portal and then laid out on portal pages.

To build the portlet:

  1. Switch to the Web perspective (if you are not already in it).
  2. Under Dynamic Web Project, right-click the project called GroovyPortlet.
  3. Select Export => WAR file.
  4. Specify a Destination and name for the WAR.For example: C:\sampleportlet\ GroovyPortlet.war
  5. Optionally, check the Overwrite existing file checkbox. If you do not check this option, you need to choose a unique name for your WAR file.
  6. Click Finish.

Installing the portlet on WebSphere Portal

You use the WebSphere Portal administrative GUI to install your portlet WAR file on the portal. Then, you can place the GroovyPortlet on any page and test it!

  1. Open WebSphere Portal as an administrator.For example, open: http://<>/wps/myportal.
  2. Type the portal administrator User ID and Password, then click the Log inbutton at the bottom. This example shows the default portal administrator user ID which is wpsadmin.
  3. Click the Administration link.
  4. In Portal Administration, click Portlet Management => Web Modules.
  5. Click the Install button.
  6. Click Browse and locate the WAR file you created, or type in the complete path to it.
  7. Click Next.
  8. Verify that you have chosen to install the correct WAR.
  9. Click Finish. You see a success message like this:

Deploying the portlet to a page

  1. If you are not already logged onto your default portal running under WebSphere Portal, log on now as an administrator: For example, log on here as wpsadmin:
  2. In portal administration, click the Administration link.
  3. Click Portal User Interface => Manage Pages.
  4. Click the My Portal link.
  5. Find the page where you want to deploy your portlet or create a new page.
  6. Click the Edit Page Layout icon.
  7. Click the Add Portlets button. There could be several on the page so pick one where you want to display the portlet.
  8. To find your portlet, in the Search by: fieldselect Title starts with. In the Search field, enter GroovyPortlet (or the name of your portlet if you named it something else), and then click the Search button.
  9. Click the Select checkbox next to the portlet you want to place on the page, and then click OK.
  10. Click Done.

Testing the portlet

Now that the portlet is deployed to a page, you can play with it!

Write your Groovy script and see result in log file

  1. Click Launch from your WebSphere Portal user interface and select the page where you have installed the portlet. For example, in the screenshot below, we launch the spike page which is where we installed our GroovyPortlet.

    You see the view mode that looks something like this.

  2. Click the edit link in the top, right corner.
  3. In the text area provided, enter some Groovy expressions to evaluate, and click Submit.
  4. Suppose you use the example shown in Listing 11 to enter some basic Groovy expressions to split a string based on a regular expression and to print out the date. (This example is taken from the Groovy site at,+or+closures).
    Listing 11. Dealing with strings in Groovy
    stringDate = "2008-04-21"
    dateArray = stringDate.split("-")
    year = dateArray[0].toInteger()
    year = year + 1
    newDate = year + "-" + dateArray[1] + "-" + dateArray[2]
    println newDate
  5. Whoa, you get nothing back on your screen! What went wrong? Your Groovy expression prints out newDate so it is not returned to the screen. A println command sends the output to STDOUT. Look at SystemOut.log for your portal server. You should see the output of your evaluated compiled Groovy code.
    [4/25/08 18:22:24:603 EDT] 0000009b SystemOutO 2009-04-21
  6. Well, going into the logs is great for an admin or developer, however the end user sees nothing. To display something on your screen, remove the line println newDate and add this line:
    response.getWriter().println ("The result of your Groovy expression is "+newDate)
  7. Re-launch the page. This time you see the output rendered on your portal page. Important: The shell.evaluate method returns what you requested to return (for example, return "Hello"). Therefore, to see the output rendered correctly in your screen, you would have to know how to get to the response writer and write to it. You learn more about this in the examples below.

    To avoid getting to and writing to the response writer every time, you can add a few lines as shown in Listing 12 in your Java which would print out the result of the expression onto the screen.

    Listing 12. Changes to to avoid calling response writer at run time
    PrintWriter out = response.getWriter();
    Object lastResult = shell.evaluate(code);
    out.println("The result of your Groovy expression is ");
  8. So what does this tell you? Have you already started thinking about how you will use this scripting-based portlet for all your mundane activities? No? Well, the next examples should get your juices flowing then.
  9. In the next few examples, you access all the variables ( request, response, logger, and so on) that were bound earlier to the Groovy shell.
  10. Once again, click the edit link and then enter the following Groovy expressions in the text area.
    Listing 13. Example to access all variables that were bound to the Groovy shell.
    import groovy.xml.*
    writer = new StringWriter()
    builder = new MarkupBuilder(writer)
    title ("This is a sample, which is created using MarkupBuilder")
    body (bgcolor:"gray")
    h1 ("Bound Variables with Markup Builder")
    table (border:"1", cellspacing:"0", cellpadding:"0")
    td (colspan:"2", "Server Info")
    td (context.getServerInfo())
    td (colspan:"2", "Port no")
    td (request.getServerPort())
    td (colspan:"2","Value for 'Test' variable")
    td (test * 2.5)
    td (colspan:"2","Logger check")"This is a test for the logger variable")
    td ("Check in your STDOut log file")
    response.getWriter().println writer.toString()

Listing 13 first creates an instance of the MarkupBuilder class that can write to character streams. Then it creates the elements of the HTML document and returns a print formatted representation of elements to the browser. You also see the variables we talked about earlier in the Complete the JSP code section in action.

When you click Submit, you see the following result in your browser.

Also, in your STDOut log file, you see this logger info message:

[5/2/08 5:05:09:197 EDT] 0000009f GroovyPortlet IThis is a test for the logger variable

Optional: To wrap up, try a sample that will create an XML document using closures and the MarkupBuilder class. (For information about closures in groovy, see Groovy Tutorial 2,+or+closures.)

Listing 14. Creating an XML document using closures
import groovy.xml.*
writer = new StringWriter()
builder = new MarkupBuilder(writer)
Members = ["Ron", "Suhel", "Karl"]
team("Web based Enablement and Support")

for (x in Members) { employee(x) }
println writer.toString()

Listing 14 attaches an employees() method to the builder instance, which represents the root node in the XML tree structure. Then it uses closures to create child nodes. The closure contains a new object, which takes parameters as map values. The code then adds three objects (team, size, and group) to the closure.

The <employee> element is a child of <employees>, which contains a declaration for the employee object and a closure that contains a collection of Members elements.

Check the log file for your output. You see an XML document similar to Listing 15.

Listing 15. Result in log file
[5/2/08 5:53:33:645 EDT] 0000009b SystemOutO
<team>Web based Enablement and Support</team>

There you have it! Revisiting our initial requirement of reducing development and deployment time, and in getting more flexibility and control, you see how we can realistically achieve that and maybe even more using the GroovyPortlet.


From the magic of the wizard to the fire of the forge, you have once again added to your ever growing tool box. You created a JSR168 portlet using a Rational IDE wizard, embedded Groovy functionality into the generated code, imported that portlet into a portal, deployed it on a page, and tested it on-the-fly. You achieved a very simple yet noble task of providing total scripting power to the user at run time. Use this quick and nimble tool wisely and let us know how you fare with it.

Downloadable resources

Related topics


Sign in or register to add and subscribe to comments.

ArticleTitle=Embedding Groovy in a JSR 168 portlet for total scripting power