Groovy in Java EE with Maven
It is quite easy to add Groovy support. Once the support is in place you can use Groovy as you would use regular Java. As a matter of fact to test out Groovy we will create a Struts2 action with it!
Following assumes we have set up a basic struts2 application using Maven:
1) In Netbeans, expand the "Project Files" and open pom.xml.
2a) Locate the maven compiler plugin, which in my poms typically looks like the following:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
2b) Edit this pom.xml such that the above looks like the following:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<compilerId>groovy-eclipse-compiler</compilerId>
<verbose>true</verbose>
<source>1.7</source>
<target>1.7</target>
</configuration>
<dependencies>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-eclipse-compiler</artifactId>
<version>2.6.0-01</version>
</dependency>
</dependencies>
</plugin>
3) Add the following dependancy
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>1.8.4</version>
<scope>provided</scope>
</dependency>
4) Download a copy of groovy-all-1.8.4.jar and copy it into the glassfish lib folder (partial path on my system is .../glassfish-3.1.2/glassfish/lib/groovy-all-1.8.4.jar).
With that bit of initial configuration out of the way we can now use Groovy quite seemlessly in our project.
Create a Struts2 action (will use the struts2 conventions plugin to avoid needless configuration)
In Netbeans 7.1, create a new package under source packages called com.kenmcwilliams.action.groovy.
Right click that folder and create a new groovy file (New->Other->Category:Groovy->Groovy Class). If the following options does not exist you will need at add Groovy (Tools(menu)->Plugins->Availible Plugins(tab)->select "Groovy and Grails").
package com.kenmcwilliams.action.groovy
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Action;
class Gest extends ActionSupport{
String greeting = "Hello from Groovy!";
public String execute(){
println "Grooooovy!"
return "success";
}
}
Create a view to render the action:
<%@taglib prefix="s" uri="/struts-tags"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Message from Groovy</title>
</head>
<body>
<h1>Message from Groovy</h1>
<s:property value="greeting"/>
</body>
</html>
That's all there is to it!