1 Introduction

Java web development as it stands today is dramatically more complicated than it needs to be. Most modern web frameworks in the Java space are over complicated and don't embrace the Don't Repeat Yourself (DRY) principles.

Dynamic frameworks like Rails, Django and TurboGears helped pave the way to a more modern way of thinking about web applications. Grails builds on these concepts and dramatically reduces the complexity of building web applications on the Java platform. What makes it different, however, is that it does so by building on already established Java technologies like Spring and Hibernate.

Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and its associated plugins. Included out the box are things like:

An easy to use Object Relational Mapping (ORM) layer built on Hibernate

An embedded Tomcat container which is configured for on the fly reloading

Dependency injection with the inbuilt Spring container

Support for internationalization (i18n) built on Spring's core MessageSource concept

A transactional service layer built on Spring's transaction abstraction

All of these are made easy to use through the power of the Groovy language and the extensive use of Domain Specific Languages (DSLs)

This documentation will take you through getting started with Grails and building web applications with the Grails framework.

1.1 What's new in Grails 2.3?

Improved Dependency Management

The default dependency resolution engine used by Grails has been changed to Aether, the dependency resolution engine used by Maven. Which engine you use can be configured in BuildConfig:

grails.project.dependency.resolver = "maven" // or ivy

Using Aether dependency resolution in Grails results in the same behavior as when using the Maven build tool, meaning improved snapshot handling, understanding of custom packaging types and so on.

In addition, the dependency-report command has been updated to print the dependency graph of the console, which helps in diagnosing dependency resolution failures. See the chapter on Dependency Resolution for more information.

Data Binder

Grails 2.3 includes a new data binding mechanism which is more flexible and easier to maintain than the data binder used in previous versions. The new data binder includes numerous enhancements including:

The legacy data binder may be used by assigning true to the grails.databinding.useSpringBinder property in grails-app/conf/Config.groovy. Note that the legacy binder does not support any of the new features provided by the new data binder.

Binding Request Body To Command Objects

If a request is made to a controller action which accepts a command object and the request includes a body, the body will be parsed and used to do data binding to the command object. This simplifies use cases where a request includes a JSON or XML body (for example) that can be bound to a command object. See the Command Objects documentation for more details.

Domain Classes As Command Objects

When a domain class is used as a command object and there is an id request parameter, the framework will retrieve the instance of the domain class from the database using the id request parameter. See the Command Objects documentation for more details.

Forked Execution

All major commands can now be forked into a separate JVM, thus isolating the build path from the runtime / test paths. Forked execution can be controlled via the BuildConfig:

Test Runner Daemon

To speed up testing when using forked execution a new daemon will start-up in the background to run tests when using interactive mode. You can restart the daemon with the restart-daemon command from interactive mode:

$ grails> restart-daemon

Server-Side REST Improvements

Grails' REST support has been significantly improved with the addition of the following features:

Command Line

The create-app command will now by default generate the command line grailsw wrapper for newly created applications. The --skip-wrapper switch may be used to prevent the wrapper from being generated.

grails create-app appname --skip-wrapper

1.2 What's new in Grails 2.2?

Namespace Support

Grails 2.2 includes improved support for managing naming conflicts between artifacts provided by an application and its plugins.

Bean names for Service artifacts provided by a plugin are now prefixed with the plugin name. For example, if a Service named com.publishing.AuthorService is provided by
a plugin named PublishingUtilities and another Service named com.bookutils.AuthorService is provided by a plugin named BookUtilities, the bean names for those services
will be publishingUtilitiesAuthorService and bookUtilitiesAuthorService respectively. If a plugin provides a Service that does not have a name which conflicts with any
other Service, then a bean alias will automatically be created that does not contain the prefix and the alias will refer to the bean referenced by the prefixed name. Service
artifacts provided directly by the application will have no prefix added to the relevant bean name. See the dependency injection and services docs.

Domain classes provided by a plugin will have their default database table name prefixed with the plugin name if the grails.gorm.table.prefix.enabled config property is
set to true. For example, if the PublishingUtilities plugin provides a domain class named Book, the default table name for that domain class will be
PUBLISHING_UTILITIES_BOOK if the grails.gorm.table.prefix.enabled config property is set to true.

URL Mappings may now include a plugin attribute to indicate that the controller referenced in the mapping is provided by a particular plugin.

The Maven plugin now resolves plugins as well as jar dependencies (previously jar dependencies were resolved by Maven and plugins by Ivy). Ivy is completely disabled leaving all dependency resolution up to Maven ensuring that evictions work as expected.

There is also a new Grails create-multi-project-build script which features initial support for Maven (Gradle coming in a future release). This script can be run from a parent directory containing Grails applications and plugins and it will generate a Maven multi-module build.

Enabling Maven in a project has been made easier with the inclusion of the create-pom command:

Grails Wrapper

The Grails Wrapper allows a Grails application to build without having to install Grails and configure a GRAILS_HOME environment variable. The wrapper includes a small shell script and a couple of small bootstrap jar files that typically would be checked in to source code control along with the rest of the project. The first time the wrapper is executed it will download and configure a Grails installation. This wrapper makes it more simple to setup a development environment, configure CI and manage upgrades to future versions of Grails. When the application is upgraded to the next version of Grails, the wrapper is updated and checked in to the source code control system and the next time developers update their workspace and run the wrapper, they will automatically be using the correct version of Grails.

Debug Option

The grails command now supports a -debug option which will startup the remote debug agent. This behavior used to be provided by the grails-debug command. grails-debug is still available but is deprecated and may be removed from a future release.

grails -debug run-app

Grails Command Aliases

The alias command may be used to define aliases for grails commands.

The following command creates an alias named rit (short for "run integration tests"):

Cache Plugin

Grails 2.1 installs the cache plugin by default. This plugin provides powerful and easy to use cache functionality to applications and plugins. The main plugin provides basic map backed caching support. For more robust caching options one of the implementation plugins should be installed and configured. See the cache-redis docs and the cache-ehcache docs for details.

New GORM Methods

In Grails 2.1.1 domain classes now have static methods named first and last to retrieve the first and last instances from the datastore. See the first and last documentation for details.

1.4 What's new in Grails 2.0?

This section covers the new features that are present in 2.0 and is broken down into sections covering the build system, core APIs, the web tier, persistence enhancements and improvements in testing. Note there are many more small enhancements and improvements, these sections just cover some of the highlights.

1.4.1 Development Environment Features

Interactive Mode and Console Enhancements

Grails 2.0 features brand new console output that is more concise and user friendly to consume. An example of the new output when running tests can be seen below:

In general Grails makes its best effort to display update information on a single line and only present the information that is crucial. This means that while in previous versions of Grails the war command produced many lines of output, in Grails 2.0 only 1 line of output is produced:

In addition simply typing 'grails' at the command line activates the new interactive mode which features TAB completion, command history and keeps the JVM running to ensure commands execute much quicker than otherwise

For more information on the new features of the console refer to the section of the user guide that covers the console and interactive mode.

Reloading Agent

Grails 2.0 reloading mechanism no longer uses class loaders, but instead uses a JVM agent to reload changes to class files. This results in greatly improved reliability when reloading changes and also ensures that the class files stored in disk remain consistent with the class files loaded in memory, which reduces the need to run the clean command.

New Test Report and Documentation Templates

There are new templates for displaying test results that are clearer and more user friendly than the previous reports:

In addition, the Grails documentation engine has received a facelift with a new template for presenting Grails application and plugin documentation:

Use a TOC for Project Docs

The old documentation engine relied on you putting section numbers into the gdoc filenames. Although convenient, this effectively made it difficult to restructure your user guide by inserting new chapters and sections. In addition, any such restructuring or renaming of section titles resulted in breaking changes to the URLs.

You can now use logical names for your gdoc files and define the structure and section titles in a YAML table-of-contents file, as described in the section on the documentation engine. The logical names appear in the URLs, so as long as you don't change those, your URLs will always remain the same no matter how much restructuring or changing of titles you do.

Grails 2.0 even provides a migrate-docs command to aid you in migrating existing gdoc user guides.

Enhanced Error Reporting and Diagnosis

Error reporting and problem diagnosis has been greatly improved with a new errors view that analyses stack traces and recursively displays problem areas in your code:

In addition stack trace filtering has been further enhanced to display only relevant trace information:

H2 Database and Console

Grails 2.0 now uses the H2 database instead of HSQLDB, and enables the H2 database console in development mode (at the URI /dbconsole) so that the in-memory database can be easily queried from the browser:

Plugin Usage Tracking

To enhance community awareness of the most popular plugins an opt-in plugin usage tracking system has been included where users can participate in providing feedback to the plugin community on which plugins are most popular.

This will help drive the roadmap and increase support of key plugins while reducing the need to support older or less popular plugins thus helping plugin development teams focus their efforts.

1.4.2 Core Features

Binary Plugins

Grails plugins can now be packaged as JAR files and published to standard maven repositories. This even works for GSP and static resources (with resources plugin 1.0.1). See the section on Binary plugins for more information.

Groovy 1.8

Spring 3.1 Profile Support

Grails' existing environment support has been bridged into the Spring 3.1 profile support. For example when running with a custom Grails environment called "production", a Spring profile of "production" is activated so that you can use Spring's bean configuration APIs to configure beans for a specific profile.

1.4.3 Web Features

Controller Actions as Methods

It is now possible to define controller actions as methods instead of using closures as in previous versions of Grails. In fact this is now the preferred way of expressing an action. For example:

// action as a method
def index() {

}
// action as a closure
def index = {

}

Binding Primitive Method Action Arguments

It is now possible to bind form parameters to action arguments where the name of the form element matches the argument name. For example given the following form:

Link Generation API

A general purpose LinkGenerator class is now available that is usable anywhere within a Grails application and not just within the context of a controller. For example if you need to generate links in a service or an asynchronous background job outside the scope of a request:

Page Rendering API

Like the LinkGenerator the new PageRenderer can be used to render GSP pages outside the scope of a web request, such as in a scheduled job or web service. The PageRenderer class features a very similar API to the render method found within controllers:

Performance Improvements

Performance of GSP page rendering has once again been improved by optimizing the GSP compiler to inline method calls where possible.

HTML5 Scaffolding

There is a new HTML5-based scaffolding UI:

jQuery by Default

The jQuery plugin is now the default JavaScript library installed into a Grails application. For backwards compatibility a Prototype plugin is available. Refer to the documentation on the Prototype plugin for installation instructions.

Easy Date Parsing

A new date method has been added to the params object to allow easy, null-safe parsing of dates:

Customizable URL Formats

The default URL Mapping mechanism supports camel case names in the URLs. The default URL for accessing an action named addNumbers in a controller named MathHelperController would be something like /mathHelper/addNumbers. Grails allows for the customization of this pattern and provides an implementation which replaces the camel case convention with a hyphenated convention that would support URLs like /math-helper/add-numbers. To enable hyphenated URLs assign a value of "hyphenated" to the grails.web.url.converter property in grails-app/conf/Config.groovy.

// grails-app/conf/Config.groovy

grails.web.url.converter = 'hyphenated'

Arbitrary strategies may be plugged in by providing a class which implements the UrlConverter interface and adding an instance of that class to the Spring application context with the bean name of grails.web.UrlConverter.BEAN_NAME. If Grails finds a bean in the context with that name, it will be used as the default converter and there is no need to assign a value to the grails.web.url.converter config property.

// src/groovy/com/myapplication/MyUrlConverterImpl.groovy

package com.myapplication

class MyUrlConverterImpl implements grails.web.UrlConverter {

String toUrlElement(String propertyOrClassName) {
// return some representation of a property or class name that should be used in URLs…
}
}

Web Flow input and output

It is now possible to provide input arguments when calling a subflow. Flows can also return output values that can be used in a calling flow.

1.4.4 Persistence Features

The GORM API

The GORM API has been formalized into a set of classes (GormStaticApi, GormInstanceApi and GormValidationApi) that get statically wired into every domain class at the byte code level. The result is better code completion for IDEs, better integration with Java and the potential for more GORM implementations for other types of data stores.

Detached Criteria and Where Queries

Grails 2.0 features support for DetachedCriteria which are criteria queries that are not associated with any session or connection and thus can be more easily reused and composed:

New findOrCreate and findOrSave Methods

Domain classes have support for the findOrCreateWhere, findOrSaveWhere, findOrCreateBy and findOrSaveBy query methods which behave just like findWhere and findBy methods except that they should never return null. If a matching instance cannot be found in the database then a new instance is created, populated with values represented in the query parameters and returned. In the case of findOrSaveWhere and findOrSaveBy, the instance is saved before being returned.

Database Migrations

A new database migration plugin has been designed and built for Grails 2.0 allowing you to apply migrations to your database, rollback changes and diff your domain model with the current state of the database.

Database Reverse Engineering

A new database reverse engineering plugin has been designed and built for Grails 2.0 that allows you to generate a domain model from an existing database schema.

Hibernate 3.6

Grails 2.0 is now built on Hibernate 3.6

Bag Collections

You can now use Hibernate Bags for mapped collections to avoid the memory and performance issues of loading large collections to enforce Set uniqueness or List order.

Unit Testing GORM

A new in-memory GORM implementation is present that supports many more features of the GORM API making unit testing of criteria queries, named queries and other previously unsupported methods possible.

Faster Unit Testing with Interactive Mode

The new interactive mode (activated by typing 'grails') greatly improves the execution time of running unit and integration tests.

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.
Sponsored by SpringSource