An Introduction to Groovy and Grails

by Harshad Oak
10/25/2006

Abstract

Java Web application frameworks have been one of the important reasons for the success of enterprise Java. One wonders if Java EE would have been so successful without the Apache Struts framework. Although the underlying programming language is important, it's often the frameworks that bring the language into the limelight. If you have been following the discussion forums, you will have noticed how that's also the case with the Ruby language and the Ruby On Rails framework. Ruby has been around for more than a decade, yet only after the Ruby On Rails framework became a runaway hit did developers start noticing the Ruby language.

Scripting languages like Ruby, PHP, and Python have been growing in popularity over the past few years and, as a result, a need developed for a Java scripting alternative and a Rails-like framework for the Java world. Groovy is the scripting language and Grails is the framework.

In this article I will look at the Web development capabilities of Groovy and then move on to the Grails framework. I will develop a sample Grails Web application and look at the various features of the framework.

What is Groovy?

Groovy is a language that has a syntax that's similar to, yet simpler than, Java. It's often referred to as a scripting/agile/dynamic language, but I would prefer to stay away from these adjectives as I feel they only end up confusing things. If Java is a wise middle-aged man, Groovy is his teenage son. Groovy has many of the old man's characteristics but is a lot wilder and a lot more fun. Both of them also work together very well.

Groovy has a lot fewer rules than Java. For example, in Java to get the standard "Hello World" output, you need to write a class, a main method with proper arguments, and more. But in Groovy, if you don't wish to write all the boilerplate code, you can get rid of the class definition and the main method and just write the one line of code that actually prints "Hello World."

So the contents of a file Hello.groovy that prints Hello World would be as follows:

println "Hello World"

The Java platform is concerned only with getting bytecodes to execute. As such, the platform does not force you to use the Java language. As long as you provide bytecodes, things will work. Groovy compiles to bytecodes, and it makes no difference to the Java platform if the bytecodes were generated from code written in Java or Groovy.

Here is an example of Groovy that shows Groovy's built-in support for lists, maps, and range and also demonstrates the simplicity of Groovy and its capacity to leverage the power of Java:

// Print Date

def mydate = new java.util.Date()

println mydate




//Iterate through a map


def numbersMAP = ['1':'ONE', '2':'TWO']

for (entry in numbersMAP) {

    println "${entry.key} = ${entry.value}" 

}


//Introducing the range

def range = 'a'..'d'


//Lists

def numberlist = [1, 2, 3, 4, 5, 6, 7, 8]

println numberlist;

println "Maximum value: ${numberlist.max()}"

Note that the above code directly uses java.util.Date and that the built-in support for collections cuts down on code required to work with lists, maps, and ranges. There are many other interesting Groovy features like closures and simplified XML processing. You can find a detailed listing at groovy.codehaus.org.

Let's now look at how you can use Groovy for Web development.

Web Development with Groovy

Most Java EE tutorials start with a basic servlet example. For Groovy Web development, you start with groovlets—the groovy parallel of servlets. If you get rid of the class and the doXX() method declarations in a servlet, what you are left with would look a lot like a groovlet. An example is a groovlet file named Login.groovy that you will place in the top-level directory of your Web application:

def username= request.getParameter("username")

def password= request.getParameter("password")



if (username == "java" && password == "developer") {

  response.sendRedirect("home.jsp")

  session = request.getSession(true);

  session.setAttribute("name", username)

}

else {

  println """

  <h1>Login Invalid</h1>

  <p>Your IP has been logged > ${request.remoteHost}</p>

  """ 

  paramMap = request.getParameterMap()

  println "<p>You Submitted:</p>" 

  for (entry in paramMap) {

  println "${entry.key} = ${entry.value}<br/>"

  }

}

You can just create a simple HTML form and send the action attribute of the form to action="Login.groovy". Next, you add these tags to your web.xml:

<servlet>

    <servlet-name>Groovy</servlet-name>

     <servlet-class>groovy.servlet.GroovyServlet</servlet-class>

</servlet>

<servlet-mapping>

      <servlet-name>Groovy</servlet-name>

     <url-pattern>*.groovy</url-pattern>

</servlet-mapping>

Now just add the required Groovy jar files to the WEB-INF/lib directory, and your Groovy Web application is ready to run on any Java EE application server.

You will have noticed the absence of semicolons in the code and also the usage of implicit variables like request and response. The other implicit variables are context, application, session, out , sout, and html.

GSPs is the groovy parallel to JSPs. You do not use a println to generate HTML; you just embed your Groovy code within an HTML page. The example in this article will use GSPs while working with Grails.

Note that because everything comes down to bytecodes in the end, groovlets and GSPs can easily work with servlets and JSPs. So you do not have to pick either groovlets and GSP or servlets and JSPs.

Let's now look at the promising Grails framework. If successful, Grails can significantly change the way you develop Java Web applications. Grails can do to Groovy what Ruby on Rails has done for Ruby.

Grails Features and Architecture

Grails attempts to use the "coding by convention" paradigm of Ruby On Rails to reduce the need for configuration files and other boilerplate code. With "coding by convention," if you have a file whose name itself tells you what the file is doing, you do not need to restate the same thing in a configuration file. The framework will look at the filename and figure things out for itself. Using "coding by convention," Grails will also auto generate a lot of things required in a Web application. Using Grails, you will have a working Web application ready in a short time and with minimal complexity. See below for an example.

Grails is based on open-source technologies like Spring, Hibernate, and SiteMesh. That's a good thing if you are already good at these technologies but a not so good thing if you dislike these technologies for some reason or think that you have to not only learn Grails but also learn three other frameworks. Although these technologies help Grails perform better, learning four frameworks will seem like too-tough entry barrier to most. The Grails documentation currently highlights its integration with Spring, Hibernate, and other programs, however I think it needs to take the opposite approach and push Grails as a simple and fast Web application development framework. The developer need not worry or care about what happens underneath.

Fortunately, once you get going with Grails, you will see that Grails hides most of the underlying complexity of these frameworks. If you just forget that it's Spring, Hibernate, and more working underneath, things will stay simple.

The three tiers of a Grails application are:

  • Web tier consisting of the views and controllers
  • Business logic tier consisting of domain classes and services
  • Persistence tier consisting of domain classes and data sources

Most frameworks have dozens of features of which very few get widely used. With Grails, the "coding by convention" paradigm and auto-generation of artifacts are these key features.

Other features of Grails are built-in support for Ajax, validations, unit testing, and functional testing. It uses the free and open-source Canoo WebTest project for functional testing of Web applications. Grails also provides integration with the Quartz Scheduler.

It's time to install the Grails framework and write your first application.

Grails Installation

The installation procedure is quite simple. The Grails download page is here: http://grails.org/Download. You can download version 0.2.1 from http://dist.codehaus.org/grails/grails-bin-0.2.1.zip. Note that Grails source code and the documentation are available as separate downloads. After you download the zip file, just extract its contents to a directory, in my case C:\groovy\grails-0.2.1\.

Create a new environment variable named GRAILS_HOME and set its value to C:\groovy\grails-0.2.1\. Next add GRAILS_HOME\bin to the PATH environment variable. That's it. You can check if the installation is okay by running the grails command on the command prompt. You should get usage information for the command.

Now that you have a working Grails installation, you're ready to create a Grails Web application.

Pages: 1, 2, 3, 4

Next Page »