I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Book Excerpt: Griffon in Action

05.24.2012
| 2659 views |
  • submit to reddit

Grails is by far the best option for building web applications in the JVM, enabling you to use features that can be found in popular Java libraries and features only found in the Groovy language. This article, based on chapter 13 of Griffon in Action, shows a bit about how Grails and Griffon can be combined to build applications that touch desktop and server with an approach aimed at high productivity and making programming fun again.

It’s hard to find a web developer who hasn’t come across an Ajax- or RIA-powered website. These technologies have become so ubiquitous that it’s hard to recall the times when Web 2.0 didn’t exist. There are myriad options for building a web application that has Ajax built in or that presents a rich interface, in both the frontend and backend tiers. Grails happens to be one of the front runners when dealing with the JVM.

If you’re a developer working on web applications and you haven’t given Grails a try, you owe it to yourself to do so. We can guarantee you won’t be disappointed.
Grails is a full-stack web development platform whose foundations lie in Spring and Hibernate, so it shouldn’t be hard for a Java developer to pick it up and get to work. But what really makes it revolutionary is its choice of default development language: Groovy—the same as in Griffon.
Grails has another ace up its sleeve: a ready-for-business command tool that’s also extensible via plugins. It’s thanks to this plugin system that building a Grails application is a breeze. Need a way to search through your data? Install the Searchable plugin. Your requirements ask for CouchDB instead of a traditional SQL store? No problem, install the CouchDB plugin. What’s that? You need to protect certain parts of an application using security realms? The Shiro plugin is here to help. You get the idea.

Out of the immense set of Grails plugins (by the team’s current count, it’s over 500), you’ll find a good number that deal with Ajax and RIAs. They’re pretty good. But, no matter which one you pick, there will be times when you require a feature that can’t be implemented because of a browser limitation. That’s when it’s time to look outside of the browser window at the space that allows you to run the browser. Yes, that’s your computer’s desktop environment. This is where Griffon comes in.
In this article, you’ll see how set up your environment to take advantage of Grails’ powerful features.

Getting Started With Grails

Setting up Grails is as easy as setting up Griffon.

  1. Point your browser to http://grails.org/Download, pick the latest stable release zip, and unpack it in the directory of your choice
  2. Set an environment variable called GRAILS_HOME, pointing to your Grails installation folder.
  3. Add GRAILS_HOME/bin to your path. In OS X and Linux, this is normally done by editing your shell configuration file (such as ~/.profile) by adding the following lines:
    export GRAILS_HOME=/opt/grails
    export PATH=$PATH:$GRAILS_HOME/bin
    
    In Windows you’ll need to go into the System Properties window to define a GRAILS_HOME variable and update your path settings.

Done? Perfect. You can verify that Grails has been installed correctly by typing grails help in your command prompt. This should display a list of available Grails commands, similar to the following:

$ grails help
| Environment set to development.....

Usage (optionals marked with *):
grails [environment]* [target] [arguments]*

Examples:
grails dev run-app
grails create-app books

This will confirm that your GRAILS_HOME has been set correctly and that the grails command is available on your path.
With installation out of the way, you’re ready to start building a Grails application.

 

Building the Grails server application

We’ll pick a book/author domain because of its simplicity. Creating our sample Bookstore application is done with a simple command:

$ grails create-app bookstore

This command will create the application’s structure and download a minimum set of plugins if you’re running Grails for the first time.
That command looks oddly similar to Griffon’s, doesn’t it? Remember that Griffon was born as a fork of the Grails codebase? We’ll put that claim to the test now.

Besides some unique concepts to Grails and Griffon, almost all commands found in both frameworks provide the same behavior.
You can run the application now, but because it’s empty you won’t see anything of use. Let’s fill it up a bit.

 

Creating domain classes

Domain classes reveal some of the differences between Grails and Griffon. One of the big differences is that Grails domain classes have access to Grails’ object relational mapping (GORM) implementation, and Griffon doesn’t provide that functionality by default:

Create two domain classes: Book and Author. Make sure you’re in the application’s directory before invoking the following commands:

$ grails create-domain-class Author
$ grails create-domain-class Book

This set of commands creates a pair of files under grails-app/domain/bookstore, aptly named Author.groovy and Book.groovy. These two classes each represent a domain object of your domain model. They both are empty at the moment. By contrast, Griffon doesn’t support domain classes out of the box. This is a concern that’s left to plugins, as domain classes aren’t a generic attribute of all Griffon applications.


Go ahead and open the two classes in your favorite editor, or, if you prefer, in your favorite IDE; Grails isn’t picky and will gladly work with any IDE or editor you throw at it. Make sure that the contents of the Author and Book domain classes match the ones in the following listings.

First, let’s look at the Grails Author domain (grails-app/domain/bookstore/Author.groovy):

package bookstore
class Author {
    static hasMany = [books: Book]                  #A
    static constraints = {
        name(blank: false)
        lastname(blank: false)
    }

    String name
    String lastname

    String toString() { "$name $lastname" }
}


#A One-to-many relationship
Now let’s look at the Grails Book domain (grails-app/domain/bookstore/Book.groovy):

package bookstore
class Book {
    static belongsTo = Author
    static constraints = {
        title(unique: true)
    }

    String title
    Author author

    String toString() { title }
}


Without going into much detail, the Author and Book classes define a pair of entities that can be persisted to the default data store. If this is the first time you’ve encountered a Grails domain class, don’t worry, they don’t bite. Besides the simple properties in each class, you’ll notice that there is a one-to-many relationship from Author to Book. You could make it a many-to-many relationship to more closely reflect the real world, but let’s keep things simple for the moment.

There’s another step that must be performed before you attempt to run the application for the first time. You must expose the domain classes to the user in some way.

Creating the controllers

With a framework other than Grails, you’d need to write HTML or use some other templating mechanism to expose your domain classes. With Grails you can let the framework take over, as long as you stick to the conventions. If you only create a pair of controller classes, one per domain class, nothing else needs to be done. Hurray for scaffolding!

Go back to your command prompt, and type the following:

$ grails create-controller Author
$ grails create-controller Book

Locate each controller under grails-app/controllers/bookstore and edit it, carefully copying the following code into the appropriate file.
First, here’s the Grails Author controller (grails-app/controllers/AuthorController.groovy):

package bookstore
class AuthorController {
    static scaffold = true 
}

Next, the Grails Book controller (grails-app/controllers/BookController.groovy):

package bookstore
class BookController {
    static scaffold = true 
}

That’s all you need for now. Don’t be fooled, though—there’s a full-blown Spring MVC-powered component behind each of these controllers.
Perfect. You’re good to go.

Running the Bookstore application

Run the application with the following command:

$ grails run-app


After a few seconds, during which the command compiles and packages the application, you’ll be instructed to visit the following address: http://localhost:8080/bookstore. Use your favorite browser to navigate to that URL. You should see a page that looks like the one in figure 1.

You’ll see a default page listing some internal details of the application, like the currently installed plugins and their versions. You’ll also notice a pair of links that point to the controller you wrote.

Click the AuthorController link. You’re now on the starting page for all create, read, update, and delete (CRUD) operations that affect an author. How is this possible? This is the power of conventions. When you instruct each controller that a domain class should be scaffolded, it generates (at compile time) the minimum required code and templates to achieve basic CRUD operations on that specific domain class.
You can play around with authors and books now. Try creating and removing some. You may end up with a screen that resembles figure 2.

Summary

Grails is by far the best option for building web applications in the JVM, enabling you to use features that can be found in popular Java libraries and features only found in the Groovy language. Griffon follows in Grails’ footsteps and aims to provide the same productivity gains but in the desktop space. The two can be combined to build applications that touch desktop and server with the same approach to development: an approach aimed at high productivity and making programming fun again.

 


 
 

 

 

 

Tags:

Comments

Peter Bliznak replied on Thu, 2012/05/24 - 11:41am

"Grails is by far the best option for building web applications in the JVM" --- tongue in cheek joke????

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.