December 18, 2014
Hot Topics:

The Search for the Holy Grail(s)

  • February 23, 2007
  • By Graeme Rocher
  • Send Email »
  • More Articles »

Grails is an MVC framework and has models, views, and controllers to cleanly separate concerns. Nevertheless, to display a simple "Hello World!" we only need to be concerned with controllers for the moment.

Controllers are core to any MVC framework, Grails being no different; and in fact the only way to handle a request in Grails is to create a controller. Out of convenience, Grails provides a target to do just this. To create a controller, run the create-controller target and enter hello as the name of your controller followed by the Enter key. Listing 3 demonstrates this in action.

Listing 3. Running the create-controller Target

>grails create-controller
   [input] Enter controller name:
hello

This will create a new controller called HelloController within the grails-app/controllers directory of the Grails application as well as an associated unit test case called grails-test/HelloTests.groovy. As mentioned previously you could have created the controller with an IDE or text editor. Regardless, the resulting controller created for you will resemble something like this:

class HelloController {
   def index = { }
}

At the moment it contains only a single action called index. Yes, controllers have actions that they delegate to. Just to provide some clarity, the effect you want to achieve is depicted in the screenshot in Figure 3.



Click here for a larger image.

Figure 3. The "Hello World!" response

In order to create the response depicted in Figure 3, you're going to make some modifications to the HelloController and add a new action called world to it. Actions are both closures and properties. Listing 4 demonstrates how to create the world action.

Listing 4. The world Action

class HelloController {
   // each action is a closure property
   def world = {
      render 'Hello World!' // render response
   }
}

The previous example defines a single action called world that renders the text "Hello World!" to the response. It does this using one of Grails' built-in methods called render. To try the "Hello World!" example, start the Grails application by running the following target:

grails run-app

Once the application has loaded, open a browser and navigate to the address shown in Figure 4 by typing the URL into the address bar (by default Grails starts up on port 8080).

Figure 4. The Grails URL format

As the diagram illustrates, Grails uses a convention to automatically configure the path to a particular action. Following Figure 4, the context path is the root of the application and could be removed altogether if the final deployment environment is the root application. The controller name part of the URL is taken from the first part of the HelloController class's name. Essentially, the controller name is calculated as the controller class name minus the Controller suffix and the first letter in lowercase. Finally, the action name at the end of the URL shown in the figure maps to an action within the controller. In this case the URL will call the world action defined in Listing 4.

The result is that the text "Hello World!" will be displayed within the browser as depicted in Figure 5. Now, say instead of merely saying hello to the user you want to do something rather more useful such as displaying the current date and time.

To get the controller to display a message as well as the date and time, you need to open up the controller again and modify the world action as shown in Listing 5.

Listing 5. Modified HelloController.groovy

class HelloController {
   def world = {
      render "Hello World it's " + new java.util.Date()
   }
}



Click here for a larger image.

Figure 5. "Hello World!" plus the date

The world action in Listing 5 concatenates the string "Hello World!" with an instance of the class java.util.Date, the standard class for handling dates in the JDK. Once the modification has been made don't stop the server, simply hit the Refresh button on the browser and note how your changes are immediately available with the action printing the "Hello World!" text followed by the current date and time. No recompilation step, no build to run, and no packaging required. Grails automatically reloads the controller at run time without you, the developer, needing to restart the server.

This simple example demonstrates some of the key features of Grails, including a glimpse into its MVC architecture, the tight integration with Java (I used java.util.Date), and the iterative development made possible by autoreloading.

The Unit Tests

Yes, it seems nowadays that no code can be written without an associated test, and rightly so. Fortunately, Grails has already created a test case for us called grails-test/HelloTests.groovy. The initial code for this unit test is the following:

class HelloTests extends GroovyTestCase {
   void testSomething() {
      // test code goes here!
   }
}

As you can see there is a testSomething method just waiting for us to populate it.

Summary

You learned how to create a Grails application, took a brief look at rendering responses with controllers, and had a glimpse at the Grails command-line targets. Clearly I only brushed the surface of Grails with the first example, and introducing the framework this way is little bit like plunging into the deep end of the Groovy and Grails world on Groovy. If you are looking for more information on the Groovy language and why it is such a great fit for web application development you might want to check out Groovy in Action produced by Manning Publications

Endnotes

  1. Anemic APIs are a common antipattern encapsulated by Martin Fowler in an article about domain models titled "Anemic Domain Model" (http://www.martinfowler.com/bliki/AnemicDomainModel.html).
  2. Bruce Tate is a big critic of Java's current development process and has written a number of books on the topic, including Bitter Java, Better, Faster, Lighter Java, and Beyond Java. His article on the "elephant" can be found at http://today.java.net/pub/a/today/2004/06/15/ejb3.html.

About the Author

Graeme Rocher is a software architect and Chief Technology Officer at SkillsMatter. He started his career in the e-learning sector as part of a team developing scalable enterprise learning management systems based on J2EE technology. He later branched into the digital TV arena where he was faced with increasingly complex requirements that required an agile approach as the ever-changing and young iDTV platforms evolved. This is where Graeme was first exposed to Groovy and he began combining Groovy with Cocoon to deliver dynamic multi-channel content management systems targeted at digital TV platforms.

Seeing an increasing trend for web delivery of services and the complexity this brought, Graeme embarked on another project to simplify this and founded Grails, a framework with the essence of Ruby on Rails, but targeted at tight Java integration. Graeme is the current project lead of Grails and is a member of the Groovy JSR-241 executive committee.

In his current role as CTO at SkillsMatter, a company specializing in Open Source training, Graeme is in charge of the companies courseware development strategy and general technical direction. As part of this role he actively works with a wide range of professionals from the Open Source community and speaks at industry conferences whenever possible on subjects related to Groovy, Grails and dynamic languages in Java.

Source of This Material

The Definitive Guide to Grails
By Graeme Rocher






ISBN: 1-59059-758-3
Published by Apress, December, 2006
Paperback: 384 pages, Retail price: $39.99
This material is from Chapter 1 of the book.
Reprinted with the publisher's permission.



Page 4 of 4



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel