Loading...

Wednesday, October 21, 2009

Groovy Goodness: Groovlets as Lightweight Servlets

Groovlets are Groovy scripts that are executed by a servlet. With Groovlets a user can request a Groovy script that is executed on the server and the results are displayed in a web browser. We only have to define a servlet in the web.xml of a Java web application, place the Groovy libraries in the web application's lib folder and we can execute Groovy scripts.

The Groovy script, or we can call it a Groovlet, has a couple of implicit variables we can use. For example reqeust, response to access the HttpServletRequest and HttpServletResponse objects. We have access to the session with the session variable. And if we want to output data we can use out, sout and html.

Let's create a Groovy script serverinfo.groovy:

def method = request.method

if (!session) {
    session = request.getSession(true)
}

if (!session.groovlet) {
    session.groovlet = 'Groovlets rock!'
}

html.html {
    head {
        title 'Groovlet info'
    }
    body {
        h1 'General info'
        ul {
            li "Method: ${method}"
            li "RequestURI: ${request.requestURI}"
            li "session.groovlet: ${session.groovlet}"
            li "application.version: ${context.version}"
        }
        
        h1 'Headers'
        ul {
            headers.each {
                li "${it.key} = ${it.value}"
            }
        }
    }
}

A simple script to start Jetty so we can run our Groovlet:

import org.mortbay.jetty.Server
import org.mortbay.jetty.servlet.*
import groovy.servlet.*

@Grab(group='org.mortbay.jetty', module='jetty-embedded', version='6.1.14')
def startJetty() {
    def jetty = new Server(9090)
    
    def context = new Context(jetty, '/', Context.SESSIONS)  // Allow sessions.
    context.resourceBase = '.'  // Look in current dir for Groovy scripts.
    context.addServlet(GroovyServlet, '*.groovy')  // All files ending with .groovy will be served.
    context.setAttribute('version', '1.0')  // Set an context attribute.
    
    jetty.start()
}

println "Starting Jetty, press Ctrl+C to stop."
startJetty()

When we run the script to start Jetty and visit http://localhost:9090/serverinfo.groovy with our browser we get the following output: