Quick and Easy Groovy for the Web

22 June 2011

Groovy can be used pretty easily to spin up some simple web pages in almost the same way one would hack out some PHP or JSP without going to the trouble to do an all-out Grails project.

The Groovy Servlet allows you to pack up the groovy-all-*.jar, a simple web.xml, and whatever *.groovy scripts you want and deploy it right into Tomcat as a plain WAR file. The Groovy Servlet page

Here's a bit of a script I put together to jump start a simple Groovlet project by packaging a WAR file from a directory of scripts. This isn't Groovy Servlet code itself, but just a command-line tool. (The Groovy Servlet page linked previously has examples for writing your own servlets.) This script will copy in the Groovy JAR and generate the basic web.xml to wire up the GroovyServlet to dynamically execute your scripts. I also have a downloadable copy of package_groovlet.groovy.

#!/usr/bin/env groovy

if (args.size() < 1) {
    print """\
        |Usage: package_groovlet.groovy <war-name>
        |Package the current directory into a Groovy Servlet war.

def war = args[0]
def embed = "${System.getenv()['GROOVY_HOME']}/embeddable"

def ant = new AntBuilder()

ant.sequential {
    delete(dir: 'build')
    mkdir(dir: 'build/WEB-INF/lib')
    copy(toDir: 'build/WEB-INF/lib') {
        fileset(dir: embed) {
            include(name: 'groovy-all-*.jar')
    copy(toDir: 'build') {
        fileset(dir: '.') {
            exclude(name: 'build/**')

new FileOutputStream('build/WEB-INF/web.xml').withWriter { webxml ->
    webxml.print """\
        <!DOCTYPE web-app PUBLIC
          "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
          "http://java.sun.com/dtd/web-app_2_3.dtd" >

ant.jar(destfile: "build/${war}", basedir: 'build')
println "Created build/${war}"

Filed Under: Work Java Computers