Thursday, November 29, 2012

A very light Groovy based web application project template

You might have heard of the project Grails is a Groovy version of Ruby on Rails like framework that let you create web application much more easier with
Dynamic scripting. Despite all that power Grails provided, it is not "light" if you look under the hood. I am not saying Grails is bad or anything. Grails is actually pretty cool to write web application with. However I found myself often want something even lighter and yet still want to prototype with Groovy. So here I will show you a maven-groovy-webapp project template that I use to get start any web application development. It's very simple, light, and yet very Groovy.

How to get started

Unzip maven-webapp-groovy.zip above and you should see these few files:

I've chosen to use GroovyServlet as a controller (it comes with Groovy!), and this let you use any scripts inside /WEB-INF/groovy directory. That's it, no further setup. That's about the only requirement you need to get a Groovy webapp started! See console.groovy as example and how it works. It's a groovy version of this JVM console

Now you can use Groovy to process any logic and even generate the HTML output if you like, but I find it even more easier to use TemplateServlet. This allow Groovy template files to be serve as view. It's very much like JSP, but it uses Groovy instead! And we know Groovy syntax are much shorter to write! See console.gt as exmaple and how it works.

The GroovyContextListener is something I wrote, and it's optional. This allow you to run any scripts during the webapp startup or shutdown states. I've created an empty init.groovy and destroy.groovy placeholder. So now you have all the hooks you need to prototype just about any web application you need.

Simplicity wins

This setup is just plain Java Servlet with Groovy loaded. I often think the more simple you get, then less bug and faster you code. No heavy frameworks, no extra learning curve, (other than basic Servlet API and Groovy/Java skills ofcourse), and off you go.

Go have fun with this Groovy webapp template! And let me know if you have some cool prototypes to show off after playing with this. :)