Shed the weight with Groovlets

Groovy, baby!
Not all web applications require a full stack framework (like Grails, Rails, Spring MVC, etc). Don’t get me wrong, the aforementioned hip frameworks are themselves lightweight (and quite powerful to boot); however, they do have an associated cost (albeit much much lower than rolling the same functionality by hand). For instance, some applications don’t require a data store (consequently, a large portion of Grails — that is, Hibernate — for example, wouldn’t be utilized). Other applications don’t really require a powerful view technology (simple services don’t require JSPs or GSPs, for instance).

Take, for example, a simple web application that populates a Google Map with markers — the map itself can be displayed on a simple .html file and via the magic of Ajax, you can quickly code an application that populates the map with interesting data– say for example, location information from some other service — Twitter, Craigslist, etc. In such a case, I don’t need a database, nor do I need the infrastructure to handle dynamic views. I do, however, require server-side processing; thus, because it’s my bag, I still need something.

In those instances were even a framework like Grails seems heavy, there is an alternative: Groovlets. Groovlet’s are simply servlets without the structure of servlets. That is, you can write simple Groovy scripts and have them execute within the context of a servlet; plus, your script has access to the normal objects you’ve come to love when coding servlets — ServletRequest, ServletResponse, ServletContext, etc.

Getting yourself up and running with Groovlet’s couldn’t be easier - simply augment a web.xml file with some copasetic mappings, add the groovy-all jar (i.e. groovy-all-1.5.7.jar) file to your web application’s WEB-INF/lib directory and you are good to go, baby!

For example, the following two phrases in my web.xml file map requests ending in .groovy to Groovy’s GroovyServlet, which handles the magic of Groovlet’s.

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
  <servlet>
      <servlet-name>GroovyServlet</servlet-name>
      <servlet-class>groovy.servlet.GroovyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
        <servlet-name>GroovyServlet</servlet-name>
        <url-pattern>*.groovy</url-pattern>
   </servlet-mapping>
</web-app>

Now any request going to a .groovy URI will invoke the GroovyServlet, which will grab the requested resource and execute it as is. The best part is that your Groovlets are simple scripts — for instance, below is a simple script that receives two parameters — username and password and returns a JSON representation of coordinates.

def name = request.getParameter('username')
def pword = request.getParameter('password')

def coordinates = getJSONLatAndLng(name, pword)

println coordinates

def getJSONLatAndLng(name, password) {
  def googleMapsSevice = new GoogleMapsService()
  def locService = new LocationService()
  def loc = locService.getLocationForUser(name, password)
  def coords = googleMapsSevice.getLocationCoordinates(loc)
  return this.getJSONForCoords(coords)
}

def getJSONForCoords(coords) {
  return new JSONObject().element("latitude", coords.latitude)
    .element("longitude", coords.longitude)
}

Note how a simple println suffices for printing output to a browser. Plus, you are free to define methods (see the two defined as getJSONLatAndLng and getJSONForCoords?) This web resource took about 12 lines of code, by the way.

I can then utilize this Groovlet, for example, to receive coordinates– in my case, I’m using jQuery to asynchronously invoke it and receive its response.

function doSubmit() {
 var tid = document.fffd.name.value;
 var pwrd = document.fffd.pword.value;

 $.getJSON("locateuser.groovy", {"username": tid,
     "password":pwrd}, function(json) {
         map.setCenter(new GLatLng(json.latitude, json.longitude), 12);
  });
}

In the code above, the Groovlet requested is called locateuser.groovy — it’s located at the web application’s root, hence no need for a full path. This is simple Javascript code located in a .html file too.

Note that I could have easily utilized RESTful principles too — in fact, I could have used GroovyReslet; however, a Groovlet in this case is probably still simpler (at the cost of elegance though).

Occasionally applications are simple enough not to warrant the infrastructure of the more established players out there — Stripes, Wicket, etc — mind you, they’re all quite nice at providing an infrastructure for building web applications (when you need it!). When faced with a simple situation (that often begs for a simple solution), take a look at Groovy’s Groovlets — these are incredibly simple and therefore quite quick to get up and running. Can you dig it, man?

Want to learn more about Groovy and Grails? Then sign up for ThirstyHead's Jump into Groovy and Grails course!

Think easyb is the coolest thing since sliced bread? Then come to my

BDD with easyb

course too!

This story, "Shed the weight with Groovlets" was originally published by JavaWorld.

Copyright © 2009 IDG Communications, Inc.