text:
1. IntroductionJava 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 technology like Spring & Hibernate.Grails is a full stack framework and attempts to solve as many pieces of the web development puzzle through the core technology and it's associated plug-ins. Included out the box are things like:
- An easy to use Object Relational Mapping (ORM) layer built on Hibernate
- An expressive view technology called Groovy Server Pages (GSP)
- A controller layer built on Spring MVC
- A command line scripting environment built on the Groovy-powered Gant
- 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
2. Getting Started
2.1 Downloading and InstallingThe first step to getting up and running with Grails is to install the distribution. To do so follow these steps:
- Download a binary distribution of Grails and extract the resulting zip file to a location of your choice
- Set the GRAILS_HOME environment variable to the location where you extracted the zip
- On Unix/Linux based systems this is typically a matter of adding something like the following
export GRAILS_HOME=/path/to/grailsto your profile
- On Windows this is typically a matter of setting an environment variable under
My Computer/Advanced/Environment Variables
- Now you need to add the
bindirectory to your
- On Unix/Linux base system this can be done by doing a
export PATH="$PATH:$GRAILS_HOME/bin"
- On windows this is done by modifying the
Pathenvironment variable under
My Computer/Advanced/Environment Variables
grails in the terminal window and see output similar to the below:
Welcome to Grails 1.0 - http://grails.org/
Licensed under Apache Standard License 2.0
Grails home is set to: /Developer/grails-1.0
No script name specified. Use 'grails help' for more info
2.2 Upgrading from previous versions of GrailsAlthough the Grails development team have tried to keep breakages to a minimum there are a number of items to consider when upgrading a Grails 1.0.x, 1.1.x, or 1.2.x applications to Grails 1.3. The major changes are described in detail below.
Upgrading from Grails 1.2.x
Plugin RepositoriesAs of Grails 1.3, Grails no longer natively supports resolving plugins against secured SVN repositories. Grails 1.2 and below's plugin resolution mechanism has been replaced by one built on Ivy the upside of which is that you can now resolve Grails plugins against Maven repositories as well as regular Grails repositories.Ivy supports a much richer setter of repository resolvers for resolving plugins with, including support for Webdav, HTTP, SSH and FTP. See the section on resolvers in the Ivy docs for all the available options and the section of plugin repositories in the user guide which explains how to configure additional resolvers.If you still need support for resolving plugins against secured SVN repositories then the IvySvn project provides a set of Ivy resolvers for resolving against SVN repositories.
Upgrading from Grails 1.1.x
Plugin pathsIn Grails 1.1.x typically a
pluginContextPath variable was used to establish paths to plugin resources. For example:
In Grails 1.2 views have been made plugin aware and this is no longer necessary:
<g:resource dir="${pluginContextPath}/images" file="foo.jpg" />
Additionally the above example will no longer link to an application image from a plugin view. To do so you need to change the above to:
<g:resource dir="images" file="foo.jpg" />
The same rules apply to the javascript and render
<g:resource contextPath="" dir="images" file="foo.jpg" />
Tag and Body return valuesTags no longer return
java.lang.String instances but instead return a
StreamCharBuffer instance. The
StreamCharBuffer class implements all the same methods as
String, however code like this may break:
In these cases you should use the
def foo = body() if(foo instanceof String) { // do something }
java.lang.CharSequence interface, which both
String and
StreamCharBuffer implement:
def foo = body() if(foo instanceof CharSequence) { // do something }
New JSONBuilderThere is a new version of
JSONBuilder which is semantically different to earlier versions of Grails. However, if your application depends on the older semantics you can still use the now deprecated implementation by settings the following property to
true in Config.groovy:
Validation on FlushGrails now executes validation routines when the underlying Hibernate session is flushed to ensure that no invalid objects are persisted. If one of your constraints (such as a custom validator) is executing a query then this can cause an addition flush resulting in a
StackOverflowError. Example:
The above code can lead to a
static constraints = { author validator: { a -> assert a != Book.findByTitle("My Book").author } }
StackOverflowError in Grails 1.2. The solution is to run the query in a new Hibernate
session (which is recommended in general as doing Hibernate work during flushing can cause other issues):
static constraints = { author validator: { a -> Book.withNewSession { assert a != Book.findByTitle("My Book").author } } }
Upgrading from Grails 1.0.x
Groovy 1.6Grails 1.1 and above ship with Groovy 1.6 and no longer supports code compiled against Groovy 1.5. If you have a library that is written in Groovy 1.5 you will need to recompile it against Groovy 1.6 before using it with Grails 1.1.
Java 5.0Grails 1.1 now no longer supports JDK 1.4, if you wish to continue using Grails then it is recommended you stick to the Grails 1.0.x stream until you are able to upgrade your JDK.
Configuration Changes1) The setting
grails.testing.reports.destDir has been renamed to
grails.project.test.reports.dir for consistency.2) The following settings have been moved from
grails-app/conf/Config.groovy to
grails.project.war.file(renamed from
grails.war.java5.dependencies option is no longer supported, since Java 5.0 is now the baseline (see above).4) The use of jsessionid (now considered harmful) is disabled by default. If your application requires jsessionid you can re-enable its usage by adding the following to
5) The syntax used to configure Log4j has changed. See the user guide section on Logging for more information.
Plugin ChangesSince 1.1, Grails no longer stores plugins inside your
PROJECT_HOME/plugins directory by default. This may result in compilation errors in your application unless you either re-install all your plugins or set the following property in
Script Changes1) If you were previously using Grails 1.0.3 or below the following syntax is no longer support for importing scripts from GRAILS_HOME:
Instead you should use the new
Ant.property(environment:"env") grailsHome = Ant.antProject.properties."env.GRAILS_HOME"includeTargets << new File ( "${grailsHome}/scripts/Bootstrap.groovy" )
grailsScript method to import a named script:
2) Due to an upgrade to Gant all references to the variable
includeTargets << grailsScript( "Bootstrap.groovy" )
Ant should be changed to
ant.3) The root directory of the project is no long on the classpath, the result is that loading a resource like this will no longer work:
Instead you should use the Java File APIs with the
def stream = getClass().classLoader.getResourceAsStream("grails-app/conf/my-config.xml")
basedir property:
new File("${basedir}/grails-app/conf/my-config.xml").withInputStream { stream -> // read the file }
Command Line ChangesThe
run-app-https and
run-war-https commands no longer exist and have been replaced by an argument to run-app:
grails run-app -https
Data Mapping Changes1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:
2) Bidirectional one-to-one associations are now mapped with a single column on the owning side and a foreign key reference. You shouldn't need to change anything, however you may want to drop the column on the inverse side as it contains duplicate data.
static mapping = { someEnum enumType:"ordinal" }
REST SupportIncoming XML requests are now no longer automatically parsed. To enable parsing of REST requests you can do so using the
parseRequest argument inside a URL mapping:
Alternatively, you can use the new
resource argument, which enables parsing by default:
2.3 Creating an ApplicationTo create a Grails application you first need to familiarize yourself with the usage of the
grails command which is used in the following manner:
In this case the command you need to execute is create-app:
grails [command name]
This will create a new directory inside the current one that contains the project. You should now navigate to this directory in terminal:
grails create-app helloworld
cd helloworld
2.4 A Hello World ExampleTo implement the typical "hello world!" example run the create-controller command:
This will create a new controller (Refer to the section on Controllers for more information) in the
grails create-controller hello
grails-app/controllers directory called
HelloController.groovy.Controllers are capable of dealing with web requests and to fulfil the "hello world!" use case our implementation needs to look like the following:
Job done. Now start-up the container with another new command called run-app:
class HelloController {
def world = {
render "Hello World!"
This will start-up a server on port 8080 and you should now be able to access your application with the URL:
grails run-app
http://localhost:8080/helloworldThe result will look something like the following screenshot:This is the Grails intro page which is rendered by the
web-app/index.gsp file. You will note it has a detected the presence of your controller and clicking on the link to our controller we can see the text "Hello World!" printed to the browser window.
2.5 Getting Set-up in an IDE
IntelliJ IDEAIntelliJ IDEA and the JetGroovy plug-in offer good support for Groovy & Grails developer. Refer to the section on Groovy and Grails support on the JetBrains website for a feature overview.To integrate Grails 1.2 to with IntelliJ run the following command to generate appropriate project files:
grails integrate-with --intellij
NetBeansA good Open Source alternative is Sun's NetBeans, which provides a Groovy/Grails plugin that automatically recognizes Grails projects and provides the ability to run Grails applications in the IDE, code completion and integration with Sun's Glassfish server. For an overview of features see the NetBeans Integration guide on the Grails website which was written by the NetBeans team.
EclipseWe recommend that users of Eclipse looking to develop Grails application take a look at SpringSource Tool Suite, which offers built in support for Grails including automatic classpath management, a GSP editor and quick access to Grails commands. See the STS Integration page for an overview.
TextMateSince Grails' focus is on simplicity it is often possible to utilize more simple editors and TextMate on the Mac has an excellent Groovy/Grails bundle available from the Texmate bundles SVN.To integrate Grails 1.2 to with TextMate run the following command to generate appropriate project files:
Alternatively TextMate can easily open any project with its command line integration by issuing the following command from the root of your project:
grails integrate-with --textmate
mate .
2.6 Convention over ConfigurationGrails uses "convention over configuration" to configure itself. This typically means that the name and location of files is used instead of explicit configuration, hence you need to familiarize yourself with the directory structure provided by Grails.Here is a breakdown and links to the relevant sections:
grails-app- top level directory for Groovy sources
conf- Configuration sources.
controllers- Web controllers - The C in MVC.
domain- The application domain.
i18n- Support for internationalization (i18n).
services- The service layer.
taglib- Tag libraries.
views- Groovy Server Pages.
scripts- Gant scripts.
src- Supporting sources
groovy- Other Groovy sources
java- Other Java sources
test- Unit and integration tests.
2.7 Running an ApplicationGrails applications can be run with the built in Tomcat server using the run-app command which will load a server on port 8080 by default:
You can specify a different port by using the
grails run-app
server.port argument:
More information on the run-app command can be found in the reference guide.
grails -Dserver.port=8090 run-app
2.8 Testing an ApplicationThe
create-* commands in Grails automatically create integration tests for you within the
test/integration directory. It is of course up to you to populate these tests with valid test logic, information on which can be found in the section on Testing. However, if you wish to execute tests you can run the test-app command as follows:
Grails also automatically generates an Ant
grails test-app
build.xml which can also run the tests by delegating to Grails' test-app command:
This is useful when you need to build Grails applications as part of a continuous integration platform such as CruiseControl.
ant test
2.9 Deploying an ApplicationGrails applications are deployed as Web Application Archives (WAR files), and Grails includes the war command for performing this task:
This will produce a WAR file under the
grails war
target directory which can then be deployed as per your container's instructions.
NEVER deploy Grails using the run-app command as this command sets Grails up for auto-reloading at runtime which has a severe performance and scalability implicationWhen deploying Grails you should always run your containers JVM with the
-server option and with sufficient memory allocation. A good set of VM flags would be:
-server -Xmx512M
2.10 Supported Java EE ContainersGrails runs on any Servlet 2.4 and above container and is known to work on the following specific container products:
- Tomcat 5.5
- Tomcat 6.0
- SpringSource tc Server
- SpringSource dm Server 1.0
- GlassFish v1 (Sun AS 9.0)
- GlassFish v2 (Sun AS 9.1)
- GlassFish v3 Prelude
- Sun App Server 8.2
- Websphere 6.1
- Websphere 5.1
- Resin 3.2
- Oracle AS
- JBoss 4.2
- Jetty 6.1
- Jetty 5
- Weblogic 7/8/9/10
2.11 Generating an ApplicationTo get started quickly with Grails it is often useful to use a feature called Scaffolding to generate the skeleton of an application. To do this use one of the
generate-* commands such as generate-all, which will generate a controller and the relevant views:
grails generate-all Book
2.12 Creating ArtefactsGrails ships with a few convenience targets such as create-controller, create-domain-class and so on that will create Controllers and different artefact types for you.
These are merely for your convenience and you can just as easily use an IDE or your favourite text editor.For example to create the basis of an application you typically need a domain model:
This will result in the creation of a domain class at
grails create-domain-class book
grails-app/domain/Book.groovy such as:
There are many such
class Book { }
create-* commands that can be explored in the command line reference guide.
3. ConfigurationIt may seem odd that in a framework that embraces "convention-over-configuration" that we tackle this topic now, but since what configuration there is typically a one off, it is best to get it out the way.With Grails' default settings you can actually develop and application without doing any configuration whatsoever. Grails ships with an embedded container and in-memory HSQLDB meaning there isn't even a database to set-up.However, typically you want to set-up a real database at some point and the way you do that is described in the following section.
3.1 Basic ConfigurationFor general configuration Grails provides a file called
grails-app/conf/Config.groovy. This file uses Groovy's ConfigSlurper which is very similar to Java properties files except it is pure Groovy hence you can re-use variables and use proper Java types!You can add your own configuration in here, for example:
Then later in your application you can access these settings in one of two ways. The most common is via the GrailsApplication object, which is available as a variable in controllers and tag libraries:
foo.bar.hello = "world"
The other way involves getting a reference to the ConfigurationHolder class that holds a reference to the configuration object:
assert "world" == grailsApplication.config.foo.bar.hello
import org.codehaus.groovy.grails.commons.* … def config = ConfigurationHolder.config assert "world" == config.foo.bar.hello
3.1.1 Built in optionsGrails also provides the following configuration options:
grails.config.locations- The location of properties files or addition Grails Config files that should be merged with main configuration
grails.enable.native2ascii- Set this to false if you do not require native2ascii conversion of Grails i18n properties files
grails.views.default.codec- Sets the default encoding regime for GSPs - can be one of 'none', 'html', or 'base64' (default: 'none'). To reduce risk of XSS attacks, set this to 'html'.
grails.views.gsp.encoding- The file encoding used for GSP source files (default is 'utf-8')
grails.mime.file.extensions- Whether to use the file extension to dictate the mime type in Content Negotiation
grails.mime.types- A map of supported mime types used for Content Negotiation
grails.serverURL- A string specifying the server URL portion of absolute links, including server name e.g. grails.serverURL="http://my.yourportal.com". See createLink.
War generation
grails.project.war.file- Sets the location where the war command should place the generated WAR file
grails.war.dependencies- A closure containing Ant builder syntax or a list of JAR filenames. Allows you to customise what libaries are included in the WAR file.
grails.war.java5.dependencies- A list of the JARs that should be included in the WAR file for JDK 1.5 and above.
grails.war.copyToWebApp- A closure containing Ant builder syntax that is legal inside an Ant copy, for example "fileset()". Allows you to control what gets included in the WAR file from the "web-app" directory.
grails.war.resources- A closure containing Ant builder syntax. Allows the application to do any other pre-warring stuff it needs to.
3.1.2 Logging
The BasicsGrails uses its common configuration mechanism to provide the settings for the underlying Log4j log system, so all you have to do is add a
log4j setting to the file
grails-app/conf/Config.groovy.So what does this
log4j setting look like? Here's a basic example:
This says that for the two 'org.codehaus.groovy.*' loggers, only messages logged at 'error' level and above will be shown. The 'org.mortbay.log' logger also shows messages at the 'warn' level. What does that mean? First of all, you have to understand how levels work.
log4j = { error 'org.codehaus.groovy.grails.web.servlet', // controllers 'org.codehaus.groovy.grails.web.pages' // GSP warn 'org.mortbay.log' }
Logging levelsThe are several standard logging levels, which are listed here in order of descending priority:
- off
- fatal
- error
- warn
- info
- debug
- trace
- all
log.error(msg) will log a message at the 'error' level. Likewise,
log.debug(msg) will log it at 'debug'. Each of the above levels apart from 'off' and 'all' have a corresponding log method of the same name.The logging system uses that message level combined with the configuration for the logger (see next section) to determine whether the message gets written out. For example, if you have an 'org.example.domain' logger configured like so:
then messages with a level of 'warn', 'error', or 'fatal' will be written out. Messages at other levels will be ignored.Before we go on to loggers, a quick note about those 'off' and 'all' levels. These are special in that they can only be used in the configuration; you can't log messages at these levels. So if you configure a logger with a level of 'off', then no messages will be written out. A level of 'all' means that you will see all messages. Simple.
warn 'org.example.domain'
LoggersLoggers are fundamental to the logging system, but they are a source of some confusion. For a start, what are they? Are they shared? How do you configure them?A logger is the object you log messages to, so in the call
log is a logger instance (of type Log). These loggers are uniquely identified by name and if two separate classes use loggers with the same name, those loggers are effectively the same instance.There are two main ways to get hold of a logger:
- use the
loginstance injected into artifacts such as domain classes, controllers and services;
- use the Commons Logging API directly.
log property, then the name of the logger is 'grails.app.<type>.<className>', where
type is the type of the artifact, say 'controller' or 'service, and
className is the fully qualified name of the artifact. For example, let's say you have this service:
then the name of the logger will be 'grails.app.service.org.example.MyService'.For other classes, the typical approach is to store a logger based on the class name in a constant static field:
package org.exampleclass MyService {
This will create a logger with the name 'org.other.MyClass' - note the lack of a 'grails.app.' prefix. You can also pass a name to the
package org.otherimport org.apache.commons.logging.LogFactoryclass MyClass { private static final log = LogFactory.getLog(this) … }
getLog() method, such as "myLogger", but this is less common because the logging system treats names with dots ('.') in a special way.
Configuring loggersYou have already seen how to configure a logger in Grails:
This example configures a logger named 'org.codehaus.groovy.grails.web.servlet' to ignore any messages sent to it at a level of 'warn' or lower. But is there a logger with this name in the application? No. So why have a configuration for it? Because the above rule applies to any logger whose name begins with 'org.codehaus.groovy.grails.servlet.' as well. For example, the rule applies to both the
log4j = { error 'org.codehaus.groovy.grails.web.servlet' }
org.codehaus.groovy.grails.web.servlet.GrailsDispatcherServlet class and the
org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest one.In other words, loggers are effectively hierarchical. This makes configuring them by package much, much simpler than it would otherwise be.The most common things that you will want to capture log output from are your controllers, services, and other artifacts. To do that you'll need to use the convention mentioned earlier: grails.app.<artifactType>.<className> . In particular the class name must be fully qualifed, i.e. with the package if there is one:
The standard artifact names used in the logging configuration are:
log4j = { // Set level for all application artifacts info "grails.app" // Set for a specific controller debug "grails.app.controller.YourController" // Set for a specific domain class debug "grails.app.domain.org.example.Book" // Set for all taglibs info "grails.app.tagLib" }
bootstrap- For bootstrap classes
dataSource- For data sources
tagLib- For tag libraries
service- For service classes
controller- For controllers
domain- For domain entities
org.codehaus.groovy.grails.commons- Core artifact information such as class loading etc.
org.codehaus.groovy.grails.web- Grails web request processing
org.codehaus.groovy.grails.web.mapping- URL mapping debugging
org.codehaus.groovy.grails.plugins- Log plugin activity
grails.spring- See what Spring beans Grails and plugins are defining
org.springframework- See what Spring is doing
org.hibernate- See what Hibernate is doing
The Root LoggerAll logger objects inherit their configuration from the root logger, so if no explicit configuration is provided for a given logger, then any messages that go to that logger are subject to the rules defined for the root logger. In other words, the root logger provides the default configuration for the logging system.Grails automatically configures the root logger to only handle messages at 'error' level and above, and all the messages are directed to the console (stdout for those with a C background). You can customise this behaviour by specifying a 'root' section in your logging configuration like so:
The above example configures the root logger to log messages at 'info' level and above to the default console appender. You can also configure the root logger to log to one or more named appenders (which we'll talk more about shortly):
log4j = { root { info() } … }
In the above example, the root logger will log to two appenders - the default 'stdout' (console) appender and a custom 'file' appender.For power users there is an alternative syntax for configuring the root logger: the root
log4j = {
appenders {
file name:'file', file:'/var/logs/mylog.log'
root {
debug 'stdout', 'file'
org.apache.log4j.Logger instance is passed as an argument to the log4j closure. This allows you to work with the logger directly:
For more information on what you can do with this
log4j = { root -> root.level = org.apache.log4j.Level.DEBUG … }
Logger instance, refer to the Log4j API documentation.Those are the basics of logging pretty well covered and they are sufficient if you're happy to only send log messages to the console. But what if you want to send them to a file? How do you make sure that messages from a particular logger go to a file but not the console? These questions and more will be answered as we look into appenders.
AppendersLoggers are a useful mechanism for filtering messages, but they don't physically write the messages anywhere. That's the job of the appender, of which there are various types. For example, there is the default one that writes messages to the console, another that writes them to a file, and several others. You can even create your own appender implementations!This diagram shows how they fit into the logging pipeline:As you can see, a single logger may have several appenders attached to it. In a standard Grails configuration, the console appender named 'stdout' is attached to all loggers through the default root logger configuration. But that's the only one. Adding more appenders can be done within an 'appenders' block:
The following appenders are available by default:
log4j = { appenders { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } }
|Logs to a JDBC connection.
|Logs to the console.
|Logs to a single file.
|Logs to rolling files, for example a new file each day.
maxFileSize and
file properties of the
RollingFileAppender instance.You can have as many appenders as you like - just make sure that they all have unique names. You can even have multiple instances of the same appender type, for example several file appenders that log to different files.If you prefer to create the appender programmatically or if you want to use an appender implementation that's not available via the above syntax, then you can simply declare an
appender entry with an instance of the appender you want:
This approach can be used to configure
import org.apache.log4j.*log4j = { appenders { appender new RollingFileAppender(name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log") } }
SMTPAppender, and more.Once you have declared your extra appenders, you can attach them to specific loggers by passing the name as a key to one of the log level methods from the previous section:
This will ensure that the 'org.codehaus.groovy.grails.commons' logger and its children send log messages to 'myAppender' as well as any appenders configured for the root logger. If you want to add more than one appender to the logger, then add them to the same level declaration:
error myAppender: "grails.app.controller.BookController"
The above example also shows how you can configure more than one logger at a time for a given appender (
error myAppender: "grails.app.controller.BookController", myFileAppender: ["grails.app.controller.BookController", "grails.app.service.BookService"], rollingFile: "grails.app.controller.BookController"
myFileAppender) by using a list.Be aware that you can only configure a single level for a logger, so if you tried this code:
you'd find that only 'fatal' level messages get logged for 'grails.app.controller.BookController'. That's because the last level declared for a given logger wins. What you probably want to do is limit what level of messages an appender writes.Let's say an appender is attached to a logger configured with the 'all' level. That will give us a lot of logging information that may be fine in a file, but makes working at the console difficult. So, we configure the console appender to only write out messages at 'info' level or above:
error myAppender: "grails.app.controller.BookController" debug myFileAppender: "grails.app.controller.BookController" fatal rollingFile: "grails.app.controller.BookController"
The key here is the
log4j = {
appenders {
console name: "stdout", threshold: org.apache.log4j.Level.INFO
threshold argument which determines the cut-off for log messages. This argument is available for all appenders, but do note that you currently have to specify a
Level instance - a string such as "info" will not work.
Custom LayoutsBy default the Log4j DSL assumes that you want to use a PatternLayout. However, there are other layouts available including:
xml- Create an XML log file
html- Creates an HTML log file
simple- A simple textual log
pattern- A Pattern layout
layout setting:
This also works for the built-in appender "stdout", which logs to the console:
log4j = { appenders { console name: "customAppender", layout: pattern(conversionPattern: "%c{2} %m%n") } }
log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n") } }
Environment-specific configurationSince the logging configuration is inside
Config.groovy, you can of course put it inside an environment-specific block. However, there is a problem with this approach: you have to provide the full logging configuration each time you define the
log4j setting. In other words, you cannot selectively override parts of the configuration - it's all or nothing.To get round this, the logging DSL provides its own environment blocks that you can put anywhere in the configuration:
The one place you can't put an environment block is inside the
log4j = { appenders { console name: "stdout", layout: pattern(conversionPattern: "%c{2} %m%n") environments { production { rollingFile name: "myAppender", maxFileSize: 1024, file: "/tmp/logs/myApp.log" } } } root { //… } // other shared config info "grails.app.controller" environments { production { // Override previous setting for 'grails.app.controller' error "grails.app.controller" } } }
root definition, but you can put the
root definition inside an environment block.
Full stacktracesWhen exceptions occur, there can be an awful lot of noise in the stacktrace from Java and Groovy internals. Grails filters these typically irrelevant details and restricts traces to non-core Grails/Groovy class packages.When this happens, the full trace is always logged to the
StackTrace logger, which by default writes its output to a file called
stacktrace.log. As with other loggers though, you can change its behaviour in the configuration. For example if you prefer full stack traces to go to the console, add this entry:
This won't stop Grails from attempting to create the stacktrace.log file - it just redirects where stack traces are written to. An alternative approach is to change the location of the 'stacktrace' appender's file:
error stdout: "StackTrace"
or, if you don't want to the 'stacktrace' appender at all, configure it as a 'null' appender:
log4j = { appenders { rollingFile name: "stacktrace", maxFileSize: 1024, file: "/var/tmp/logs/myApp-stacktrace.log" } }
You can of course combine this with attaching the 'stdout' appender to the 'StackTrace' logger if you want all the output in the console.Finally, you can completely disable stacktrace filtering by setting the
log4j = { appenders { 'null' name: "stacktrace" } }
grails.full.stacktrace VM property to
grails -Dgrails.full.stacktrace=true run-app
Masking Request Parameters From Stacktrace LogsWhen Grails logs a stacktrace, the log message may include the names and values of all of the request parameters for the current request. To mask out the values of secure request parameters, specify the parameter names in the
grails.exceptionresolver.params.exclude config property:
Request parameter logging may be turned off altogether by setting the
grails.exceptionresolver.params.exclude = ['password', 'creditCard']
grails.exceptionresolver.logRequestParameters config property to
false. The default value is
true when the application is running in DEVELOPMENT mode and
false for all other modes.
Logger inheritanceEarlier, we mentioned that all loggers inherit from the root logger and that loggers are hierarchical based on '.'-separated terms. What this means is that unless you override a parent setting, a logger retains the level and the appenders configured for that parent. So with this configuration:
all loggers in the application will have a level of 'debug' and will log to both the 'stdout' and 'file' appenders. What if you only want to log to 'stdout' for a particular logger? In that case, you need to change the 'additivity' for a logger.Additivity simply determines whether a logger inherits the configuration from its parent. If additivity is false, then its not inherited. The default for all loggers is true, i.e. they inherit the configuration. So how do you change this setting? Here's an example:
log4j = {
appenders {
file name:'file', file:'/var/logs/mylog.log'
root {
debug 'stdout', 'file'
So when you specify a log level, add an 'additivity' named argument. Note that you when you specify the additivity, you must configure the loggers for a named appender. The following syntax will not work:
log4j = { appenders { … } root { … } info additivity: false stdout: ["grails.app.controller.BookController", "grails.app.service.BookService"] }
info additivity: false, "grails.app.controller.BookController", "grails.app.service.BookService"
3.1.3 GORMGrails provides the following GORM configuration options:
grails.gorm.failOnError- If set to
true, causes the save() method on domain classes to throw a
grails.validation.ValidationExceptionif validation fails during a save. This option may also be assigned a list of Strings representing package names. If the value is a list of Strings then the failOnError behavior will only be applied to domain classes in those packages (including sub-packages). See the save method docs for more information.
Enable failOnError for domain classes by package…
grails.gorm.failOnError = ['com.companyname.somepackage', 'com.companyname.someotherpackage']
grails.gorm.autoFlush= If set to
true, causes the merge, save and delete methods to flush the session, replacing the need to do something like
save(flush: true).
3.2 Environments
Per Environment ConfigurationGrails supports the concept of per environment configuration. Both the
Config.groovy file and the
DataSource.groovy file within the
grails-app/conf directory can take advantage of per environment configuration using the syntax provided by ConfigSlurper As an example consider the following default
DataSource definition provided by Grails:
Notice how the common configuration is provided at the top level and then an
dataSource { pooled = false driverClassName = "org.hsqldb.jdbcDriver" username = "sa" password = "" } environments { development { dataSource { dbCreate = "create-drop" // one of 'create', 'createeate-drop','update' url = "jdbc:hsqldb:mem:devDB" } } test { dataSource { dbCreate = "update" url = "jdbc:hsqldb:mem:testDb" } } production { dataSource { dbCreate = "update" url = "jdbc:hsqldb:file:prodDb;shutdown=true" } } }
environments block specifies per environment settings for the
dbCreate and
url properties of the
DataSource. This syntax can also be used within
Packaging and Running for Different EnvironmentsGrails' command line has built in capabilities to execute any command within the context of a specific environment. The format is:
In addition, there are 3 preset environments known to Grails:
grails [environment] [command name]
prod, and
test for
production and
test. For example to create a WAR for the
test environment you could do:
If you have other environments that you need to target you can pass a
grails test war
grails.env variable to any command:
grails -Dgrails.env=UAT run-app
Programmatic Environment DetectionWithin your code, such as in a Gant script or a bootstrap class you can detect the environment using the Environment class:
import grails.util.Environment...switch(Environment.current) { case Environment.DEVELOPMENT: configureForDevelopment() break case Environment.PRODUCTION: configureForProduction() break }
Per Environment BootstrappingIts often desirable to run code when your application starts up on a per-environment basis. To do so you can use the
grails-app/conf/BootStrap.groovy file's support for per-environment execution:
def init = { ServletContext ctx -> environments { production { ctx.setAttribute("env", "prod") } development { ctx.setAttribute("env", "dev") } } ctx.setAttribute("foo", "bar") }
Generic Per Environment ExecutionThe previous
BootStrap example uses the
grails.util.Environment class internally to execute. You can also use this class yourself to execute your own environment specific logic:
Environment.executeForCurrentEnvironment { production { // do something in production } development { // do something only in development } }
3.3 The DataSourceSince Grails is built on Java technology setting up a data source requires some knowledge of JDBC (the technology that doesn't stand for Java Database Connectivity).Essentially, if you are using another database other than HSQLDB you need to have a JDBC driver. For example for MySQL you would need Connector/JDrivers typically come in the form of a JAR archive. Drop the JAR into your project's
lib directory.Once you have the JAR in place you need to get familiar Grails' DataSource descriptor file located at
grails-app/conf/DataSource.groovy. This file contains the dataSource definition which includes the following settings:
driverClassName- The class name of the JDBC driver
username- The username used to establish a JDBC connection
password- The password used to establish a JDBC connection
url- The JDBC URL of the database
dbCreate- Whether to auto-generate the database from the domain model or not - one of 'create-drop', 'create', 'update' or 'validate'
pooled- Whether to use a pool of connections (defaults to true)
logSql- Enable SQL logging to stdout
dialect- A String or Class that represents the Hibernate dialect used to communicate with the database. See the org.hibernate.dialect package for available dialects.
properties- Extra properties to set on the DataSource bean. See the Commons DBCP BasicDataSource documentation.
dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "yourUser" password = "yourPassword" }
When configuring the DataSource do not include the type or the def keyword before any of the configuration settings as Groovy will treat these as local variable definitions and they will not be processed. For example the following is invalid:
Example of advanced configuration using extra properties:
dataSource { boolean pooled = true // type declaration results in local variable … }
dataSource { pooled = true dbCreate = "update" url = "jdbc:mysql://localhost/yourDB" driverClassName = "com.mysql.jdbc.Driver" dialect = org.hibernate.dialect.MySQL5InnoDBDialect username = "yourUser" password = "yourPassword" properties { maxActive = 50 maxIdle = 25 minIdle = 5 initialSize = 5 minEvictableIdleTimeMillis = 60000 timeBetweenEvictionRunsMillis = 60000 maxWait = 10000 validationQuery = "/* ping */" } }
More on dbCreateHibernate can automatically create the database tables required for your domain model. You have some control over when and how it does this through the
dbCreate property, which can take these values:
- create - Creates the schema on startup, clearing any existing tables and data first.
- create-drop - Same as create, but also drops the tables when the application shuts down.
- update - Updates the current schema without dropping any tables or data. Note that this can't properly handle certain schema changes like column renames (you're left with the old column containing the existing data).
- validate - Checks that the current schema matches the domain model, but doesn't modify the database in any way.
dbCreate setting completely, which is recommended once you have an application and database in production. Database changes then have to be managed through proper migrations, either via SQL scripts or a migration tool like Liquibase (for which there is a plugin).
3.3.1 DataSources and EnvironmentsThe previous example configuration assumes you want the same config for all environments: production, test, development etc.Grails' DataSource definition is "environment aware", however, so you can do:
dataSource {
// common settings here
environments {
production {
dataSource {
url = "jdbc:mysql://liveip.com/liveDb"
3.3.2 JNDI DataSources
Referring to a JNDI DataSourceSince many Java EE containers typically supply
DataSource instances via the Java Naming and Directory Interface (JNDI). Sometimes you are required to look-up a
DataSource via JNDI.Grails supports the definition of JNDI data sources as follows:
The format on the JNDI name may vary from container to container, but the way you define the
dataSource {
jndiName = "java:comp/env/myDataSource"
DataSource remains the same.
Configuring a Development time JNDI resourceThe way in which you configure JNDI data sources at development time is plugin dependent. Using the Tomcat plugin you can define JNDI resources using the
grails.naming.entries setting in
grails.naming.entries = [ "bean/MyBeanFactory": [ auth: "Container", type: "com.mycompany.MyBean", factory: "org.apache.naming.factory.BeanFactory", bar: "23" ], "jdbc/EmployeeDB": [ type: "javax.sql.DataSource", //required auth: "Container", // optional description: "Data source for Foo", //optional driverClassName: "org.hsql.jdbcDriver", url: "jdbc:HypersonicSQL:database", username: "dbusername", password: "dbpassword", maxActive: "8", maxIdle: "4" ], "mail/session": [ type: "javax.mail.Session, auth: "Container", "mail.smtp.host": "localhost" ] ]
3.3.3 Automatic Database MigrationThe
dbCreate property of the
DataSource definition is important as it dictates what Grails should do at runtime with regards to automatically generating the database tables from GORM classes. The options are:
create-drop- Drops and re-creates the database when Grails starts, and drops the schema at the end of a clean shutdown.
create- Drops and re-creates the database when Grails starts, but doesn't drop the schema at the end of a clean shutdown.
update- Creates the database if it doesn't exist, and modifies it if it does exist. The modifications are rather basic though, and generally only include adding missing columns and tables. Will not drop or modify anything.
validate- Makes no changes to your database. Compares the configuration with the existing database schema and reports warnings.
- any other value - does nothing. Don't specify any value if you want to manage databases yourself or by using a 3rd-party tool.
BothIn development mode
createwill destroy all existing data hence use with caution!
dbCreate is by default set to "create-drop":
What this does is automatically drop and re-create the database tables on each restart of the application. Obviously this may not be what you want in production.
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
Although Grails does not currently support Rails-style Migrations out of the box, there are currently three plugins that provide similar capabilities to Grails: Autobase (http://wiki.github.com/RobertFischer/autobase), The LiquiBase plugin and the DbMigrate plugin both of which are available via the
grails list-plugins command
3.3.4 Transaction-aware DataSource ProxyThe actual
dataSource bean is wrapped in a transaction-aware proxy so you will be given the connection that's being used by the current transaction or Hibernate
Session if one is active.If this were not the case, then retrieving a connection from the
dataSource would be a new connection, and you wouldn't be able to see changes that haven't been committed yet (assuming you have a sensible transaction isolation setting, e.g.
READ_COMMITTED or better).The "real" unproxied
dataSource is still available to you if you need access to it; its bean name is
dataSourceUnproxied.You can access this bean like any other Spring bean, i.e. using dependency injection:
or by pulling it from the
class MyService { def dataSourceUnproxied … }
def dataSourceUnproxied = ctx.dataSourceUnproxied
3.4 Externalized ConfigurationSome deployments require that configuration be sourced from more than one place and be changeable without requiring a rebuild of the application. In order to support deployment scenarios such as these the configuration can be externalized. To do so you need to point Grails at the locations of the configuration files Grails should be using by adding a
grails.config.locations setting in
In the above example we're loading configuration files (both Java properties files and ConfigSlurper configurations) from different places on the classpath and files located in
grails.config.locations = [ "classpath:${appName}-config.properties", "classpath:${appName}-config.groovy", "file:${userHome}/.grails/${appName}-config.properties", "file:${userHome}/.grails/${appName}-config.groovy"]
USER_HOME.It is also possible to load config by specifying a class that is a config script.
This can be useful in situations where the config is either coming from a plugin or some other part of your application. A typical use for this is re-using configuration provided by plugins across multiple applications.Ultimately all configuration files get merged into the
grails.config.locations = [com.my.app.MyConfig]
config property of the GrailsApplication object and are hence obtainable from there.Values that have the same name as previously defined values will overwrite the existing values, and the pointed to configuration sources are loaded in the order in which they are defined.
Config DefaultsThe configuration values contained in the locations described by the
grails.config.locations property will override any values defined in your application
Config.groovy file which may not be what you want. You may want to have a set of default values be be loaded that can be overridden in either your application's
Config.groovy file or in a named config location. For this you can use the
grails.config.defaults.locations property.This property supports the same values as the
grails.config.locations property (i.e. paths to config scripts, property files or classes), but the config described by
grails.config.defaults.locations will be loaded before all other values and can therefore be overridden. Some plugins use this mechanism to supply one or more sets of default configuration that you can choose to include in your application config.
Grails also supports the concept of property place holders and property override configurers as defined in Spring For more information on these see the section on Grails and Spring
3.5 Versioning
Versioning BasicsGrails has built in support for application versioning. When you first create an application with the create-app command the version of the application is set to
0.1. The version is stored in the application meta data file called
application.properties in the root of the project.To change the version of your application you can run the set-version command:
The version is used in various commands including the war command which will append the application version to the end of the created WAR file.
grails set-version 0.2
Detecting Versions at RuntimeYou can detect the application version using Grails' support for application metadata using the GrailsApplication class. For example within controllers there is an implicit grailsApplication variable that can be used:
If it is the version of Grails you need you can use:
def version = grailsApplication.metadata['app.version']
or the
def grailsVersion = grailsApplication.metadata['app.grails.version']
GrailsUtil class:
import grails.util.*
def grailsVersion = GrailsUtil.grailsVersion
3.6 Project DocumentationSince Grails 1.2, the documentation engine that powers the creation of this documentation is available to your Grails projects.The documentation engine uses a variation on the Textile syntax to automatically create project documentation with smart linking, formatting etc.
Creating project documentationTo use the engine you need to follow a few conventions. Firstly you need to create a
src/docs/guide directory and then have numbered text files using the
gdoc format. For example:
The title of each chapter is taken from the file name. The order is dictated by the numerical value at the beginning of the file name.
+ src/docs/guide/1. Introduction.gdoc + src/docs/guide/2. Getting Started.gdoc
Creating reference itemsReference items appear in the left menu on the documentation and are useful for quick reference documentation. Each reference item belongs to a category and a category is a directory located in the
src/docs/ref directory. For example say you defined a new method called
renderPDF, that belongs to a category called
Controllers this can be done by creating a gdoc text file at the following location:
+ src/ref/Controllers/renderPDF.gdoc
Configuring Output PropertiesThere are various properties you can set within your
grails-app/conf/Config.groovy file that customize the output of the documentation such as:
- grails.doc.authors - The authors of the documentation
- grails.doc.license - The license of the software
- grails.doc.copyright - The copyright message to display
- grails.doc.footer - The footer to use
Generating DocumentationOnce you have created some documentation (refer to the syntax guide in the next chapter) you can generate an HTML version of the documentation using the command:
This command will output an
grails doc
docs/manual/index.html which can be opened to view your documentation.
Documentation SyntaxAs mentioned the syntax is largely similar to Textile or Confluence style wiki markup. The following sections walk you through the syntax basics.
Basic FormattingMonospace:
Italic: italic
Bold: bold
LinkingThere are several ways to create links with the documentation generator. A basic external link can either be defined using confluence or textile style markup:
For links to other sections inside the user guide you can use the
[SpringSource|http://www.springsource.com/] or "SpringSource":http://www.springsource.com/
guide: prefix:
The documentation engine will warn you if any links to sections in your guide break. Sometimes though it is preferable not to hard code the actual names of guide sections since you may move them around. To get around this you can create an alias inside
[Intro|guide:1. Introduction]
And then the link becomes:
grails.doc.alias.intro="1. Introduction"
This is useful since if you linked the to "1. Introduction" chapter many times you would have to change all of those links.To link to reference items you can use a special syntax:
In this case the category of the reference item is on the left hand side of the | and the name of the reference item on the right.Finally, to link to external APIs you can use the
api: prefix. For example:
The documentation engine will automatically create the appropriate javadoc link in this case. If you want to add additional APIs to the engine you can configure them in
grails-app/conf/Config.groovy. For example:
The above example configures classes within the
org.hibernate package to link to the Hibernate website's API docs.
Lists and HeadingsHeadings can be created by specifying the letter 'h' followed by a number and then a dot:
Unordered lists are defined with the use of the * character:
h3.<space>Heading3 h4.<space>Heading4
Numbered lists can be defined with the # character:
* item 1 ** subitem 1 ** subitem 2 * item 2
Tables can be created using the
# item 1
table macro:
*Name* | *Number*
Albert | 46
Wilma | 1348
James | 12
Code and NotesYou can define code blocks with the
code macro:
class Book {
String title
The example above provides syntax highlighting for Java and Groovy code, but you can also highlight XML markup:
class Book {
String title
There are also a couple of macros for displaying notes and warnings:Note:
{code:xml} <hello>world</hello> {code}
This is a note!
{note} This is a note! {note}
This is a warning!
{warning} This is a warning! {warning}
3.7 Dependency ResolutionIn order to control how JAR dependencies are resolved Grails features (since version 1.2) a dependency resolution DSL that allows you to control how dependencies for applications and plugins are resolved.Inside the
grails-app/conf/BuildConfig.groovy file you can specify a
grails.project.dependency.resolution property that configures how dependencies are resolved:
The default configuration looks like the following:
grails.project.dependency.resolution = { // config here }
The details of the above will be explained in the next few sections.
grails.project.dependency.resolution = { // inherit Grails' default dependencies inherits("global") { // uncomment to disable ehcache // excludes 'ehcache' } log "warn" // log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose' repositories { grailsPlugins() grailsHome() grailsCentral() // uncomment the below to enable remote dependency resolution // from public Maven repositories //mavenLocal() //mavenCentral() //mavenRepo "http://snapshots.repository.codehaus.org" //mavenRepo "http://repository.codehaus.org" //mavenRepo "http://download.java.net/maven/2/" //mavenRepo "http://repository.jboss.com/maven2/" } dependencies { // specify dependencies here under either 'build', 'compile', 'runtime', 'test' or 'provided' scopes eg. // runtime 'mysql:mysql-connector-java:5.1.5' } }
3.7.1 Configurations and DependenciesGrails features 5 dependency resolution configurations (or 'scopes') which you can take advantage of:
build: Dependencies for the build system only
compile: Dependencies for the compile step
runtime: Dependencies needed at runtime but not for compilation (see above)
test: Dependencies needed for testing but not at runtime (see above)
provided: Dependencies needed at development time, but not during WAR deployment
dependencies block you can specify a dependency that falls into one of these configurations by calling the equivalent method. For example if your application requires the MySQL driver to function at
runtime you can specify as such:
The above uses the string syntax which is
runtime 'com.mysql:mysql-connector-java:5.1.5'
group:name:version. You can also use a map-based syntax:
In Maven terminology,
runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'
group corresponds to an artifact's
groupId and
name corresponds to its
artifactId.Multiple dependencies can be specified by passing multiple arguments:
runtime 'com.mysql:mysql-connector-java:5.1.5', 'net.sf.ehcache:ehcache:1.6.1'// Orruntime( [group:'com.mysql', name:'mysql-connector-java', version:'5.1.5'], [group:'net.sf.ehcache', name:'ehcache', version:'1.6.1'] )
Disabling transitive dependency resolutionBy default, Grails will not only get the JARs and plugins that you declare, but it will also get their transitive dependencies. This is usually what you want, but there are occasions where you want a dependency without all its baggage. In such cases, you can disable transitive dependency resolution on a case-by-case basis:
runtime('com.mysql:mysql-connector-java:5.1.5', 'net.sf.ehcache:ehcache:1.6.1') { transitive = false }// Or runtime group:'com.mysql', name:'mysql-connector-java', version:'5.1.5', transitive:false
Excluding specific transitive dependenciesA far more common scenario is where you want the transitive dependencies, but some of them cause issues with your own dependencies or are unnecessary. For example, many Apache projects have 'commons-logging' as a transitive dependency, but it shouldn't be included in a Grails project (we use SLF4J). That's where the
excludes option comes in:
As you can see, you can either exclude dependencies by their artifact ID (also known as a module name) or any combination of group and artifact IDs (if you use the map notation). You may also come across
runtime('com.mysql:mysql-connector-java:5.1.5', 'net.sf.ehcache:ehcache:1.6.1') { excludes "xml-apis", "commons-logging" }// Or runtime(group:'com.mysql', name:'mysql-connector-java', version:'5.1.5') { excludes([ group: 'xml-apis', name: 'xml-apis'], [ group: 'org.apache.httpcomponents' ], [ name: 'commons-logging' ])
exclude as well, but that can only accept a single string or map:
runtime('com.mysql:mysql-connector-java:5.1.5', 'net.sf.ehcache:ehcache:1.6.1') {
exclude "xml-apis"
Using Ivy module configurationsIf you are using Ivy module configurations and wish to depend on a specific configuration of a module, you can use the
dependencyConfiguration method to specify the configuration to use.
If the dependency configuration is not explicitly set, the configuration named
provided("my.org:web-service:1.0") { dependencyConfiguration "api" }
"default" will be used (which is also the correct value for dependencies coming from Maven style repositories).
3.7.2 Dependency Repositories
Remote RepositoriesGrails, when installed, does not use any remote public repositories. There is a default
grailsHome() repository that will locate the JAR files Grails needs from your Grails installation. If you want to take advantage of a public repository you need to specify as such inside the
repositories block:
In this case the default public Maven repository is specified. To use the SpringSource Enterprise Bundle Repository you can use the
repositories { mavenCentral() }
ebr() method:
You can also specify a specific Maven repository to use by URL:
repositories { ebr() }
repositories {
mavenRepo "http://repository.codehaus.org"
Controlling Repositories Inherited from PluginsA plugin you have installed may define a reference to a remote repository just as an application can. By default your application will inherit this repository definition when you install the plugin.If you do not wish to inherit repository definitions from plugins then you can disable repository inheritance:
In this case your application will not inherit any repository definitions from plugins and it is down to you to provide appropriate (possibly internal) repository definitions.
repositories {
inherit false
Local ResolversIf you do not wish to use a public Maven repository you can specify a flat file repository:
To specify your local Maven cache (
repositories { flatDir name:'myRepo', dirs:'/path/to/repo' }
~/.m2/repository) as a repository:
repositories { mavenLocal() }
Custom ResolversIf all else fails since Grails builds on Apache Ivy you can specify an Ivy resolver:
A common question is whether it's possible to pull dependencies from a repository using SSH. The answer is yes! Ivy comes with a dedicated resolver that you can configure and include in your project like so:
/* * Configure our resolver. */ def libResolver = new org.apache.ivy.plugins.resolver.URLResolver() ['libraries', 'builds'].each { libResolver.addArtifactPattern("http://my.repository/${it}/[organisation]/[module]/[revision]/[type]s/[artifact].[ext]") libResolver.addIvyPattern("http://my.repository/${it}/[organisation]/[module]/[revision]/[type]s/[artifact].[ext]") } libResolver.name = "my-repository" libResolver.settings = ivySettingsresolver libResolver
If you're going to use the SSH resolver, then you will need to download the JSch JAR and add it to Grails' classpath. You can either do this by adding its path to the
import org.apache.ivy.plugins.resolver.SshResolver … repositories { ... def sshResolver = new SshResolver( name: "myRepo", user: "username", host: "dev.x.com", keyFile: new File("/home/username/.ssh/id_rsa"), m2compatible: true) sshResolver.addArtifactPattern("/home/grails/repo/[organisation]/[artifact]/[revision]/[artifact]-[revision].[ext]") sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy() sshResolver.changingPattern = ".*SNAPSHOT" sshResolver.setCheckmodified(true) resolver sshResolver }
CLASSPATH environment variable or by passing the path in the Grails command line:
The environment variable is more convenient, but be aware that it affects many Java applications. An alternative on Unix is to create an alias for
grails -classpath /path/to/jsch compile|run-app|etc.
grails -classpath ... so that you don't have to type the extra arguments each time.
AuthenticationIf your repository requires some form of authentication you can specify as such using a
credentials block:
The above can also be placed in your
credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" }
USER_HOME/.grails/settings.groovy file using the
grails.project.ivy.authentication setting:
grails.project.ivy.authentication = { credentials { realm = ".." host = "localhost" username = "myuser" password = "mypass" } }
3.7.3 Debugging ResolutionIf you are having trouble getting a dependency to resolve you can enable more verbose debugging from the underlying engine using the
log method:
// log level of Ivy resolver, either 'error', 'warn', 'info', 'debug' or 'verbose'
log "warn"
3.7.4 Inherited DependenciesBy default every Grails application inherits a bunch of framework dependencies. This is done through the line:
Inside the
inherits "global"
BuildConfig.groovy file. If you wish exclude certain inherited dependencies then you can do so using the
excludes method:
inherits("global") { excludes "oscache", "ehcache" }
3.7.5 Providing Default DependenciesMost Grails applications will have runtime dependencies on a lot of jar files that are provided by the Grails framework. These include libraries like Spring, Sitemesh, Hibernate etc. When a war file is created, all of these dependencies will be included in it. But, an application may choose to exclude these jar files from the war. This is useful when the jar files will be provided by the container, as would normally be the case if multiple Grails applications are deployed to the same container. The dependency resolution DSL provides a mechanism to express that all of the default dependencies will be provided by the container. This is done by invoking the
defaultDependenciesProvided method and passing
true as an argument:
Note that
grails.project.dependency.resolution = { defaultDependenciesProvided true // all of the default dependencies will be "provided" by the container inherits "global" // inherit Grails' default dependencies repositories { grailsHome() // … } dependencies { // … } }
defaultDependenciesProvided must come before
inherits, otherwise the Grails dependencies will be included in the war.
3.7.6 Dependency ReportsAs mentioned in the previous section a Grails application consists of dependencies inherited from the framework, the plugins installed and the application dependencies itself.To obtain a report of an application's dependencies you can run the dependency-report command:
This will output a report to the
grails dependency-report
target/dependency-report directory by default. You can specify which configuration (scope) you want a report for by passing an argument containing the configuration name:
grails dependency-report runtime
3.7.7 Plugin JAR Dependencies
Specifying Plugin JAR dependenciesThe way in which you specify dependencies for a plugin is identical to how you specify dependencies in an application. When a plugin is installed into an application the application automatically inherits the dependencies of the plugin.If you want to define a dependency that is resolved for use with the plugin but not exported to the application then you can set the
export property of the dependency:
In this case the
compile( 'org.hibernate:hibernate-core:3.3.1.GA') {
export = false
hibernate-core dependency will be available only to the plugin and not resolved as an application dependency. Alternatively, if you're using the map syntax:
compile( group: 'org.hibernate', name: 'hibernate-core', version: '3.3.1.GA', export: false )
You can use
exported = falseinstead of
export = false, but we recommend the latter because it's consistent with the map argument.
Overriding Plugin JAR Dependencies in Your ApplicationIf a plugin is using a JAR which conflicts with another plugin, or an application dependency then you can override how a plugin resolves its dependencies inside an application using exclusions. For example:
In this case the application explicitly declares a dependency on the "hibernate" plugin and specifies an exclusion using the
plugins { runtime( "org.grails.plugins:hibernate:1.3.0" ) { excludes "javassist" } }dependencies { runtime "javassist:javassist:3.4.GA" }
excludes method, effectively excluding the javassist library as a dependency.
3.7.8 Maven IntegrationWhen using the Grails Maven plugin, Grails' dependency resolution mechanics are disabled as it is assumed that you will manage dependencies via Maven's
pom.xml file.However, if you would like to continue using Grails regular commands like run-app, test-app and so on then you can tell Grails' command line to load dependencies from the Maven
pom.xml file instead.To do so simply add the following line to your
The line
grails.project.dependency.resolution = {
pom true
pom true tells Grails to parse Maven's
pom.xml and load dependencies from there.
3.7.9 Deploying to a Maven RepositoryIf you are using Maven to build your Grails project, you can use the standard Maven targets
mvn install and
mvn deploy.
If not, you can deploy a Grails project or plugin to a Maven repository using the maven-publisher plugin.The plugin provides the ability to publish Grails projects and plugins to local and remote Maven repositories. There are two key additional targets added by the plugin:
- maven-install - Installs a Grails project or plugin into your local Maven cache
- maven-deploy - Deploys a Grails project or plugin to a remote Maven repository
pom.xml for you unless a
pom.xml is already present in the root of the project, in which case this
pom.xml file will be used.
maven-install command will install the Grails project or plugin artifact into your local Maven cache:
In the case of plugins, the plugin zip file will be installed, whilst for application the application WAR file will be installed.
grails maven-install
maven-deploy command will deploy a Grails project or plugin into a remote Maven repository:
It is assumed that you have specified the necessary
grails maven-deploy
<distributionManagement> configuration within a
pom.xml or that you specify the
id of the remote repository to deploy to:
grails maven-deploy --repository=myRepo
repository argument specifies the 'id' for the repository. You need to configure the details of the repository specified by this 'id' within your
grails-app/conf/BuildConfig.groovy file or in your
USER_HOMER/.grails/settings.groovy file:
The syntax for configuring remote repositories matches the syntax from the remoteRepository element in the Ant Maven tasks. For example the following XML:
grails.project.dependency.distribution = { localRepository = "/path/to/my/local" remoteRepository(id:"myRepo", url:"http://myserver/path/to/repo") }
Can be expressed as:
<remoteRepository id="myRepo" url="scp://localhost/www/repository"> <authentication username="..." privateKey="${user.home}/.ssh/id_dsa"/> </remoteRepository>
By default the plugin will try to detect the protocol to use from the URL of the repository (ie "http" from "http://.." etc.), however if you need to explicitly specify a different protocol you can do:
remoteRepository(id:"myRepo", url:"scp://localhost/www/repository") { authentication username:"...", privateKey:"${userHome}/.ssh/id_dsa" }
The available protocols are:
grails maven-deploy --repository=myRepo --protocol=webdav
- http
- scp
- scpexe
- ftp
- webdav
Groups, Artifacts and VersionsMaven defines the notion of a 'groupId', 'artifactId' and a 'version'. This plugin pulls this information from the Grails project conventions or plugin descriptor.
ProjectsFor applications this plugin will use the Grails application name and version provided by Grails when generating the
pom.xml file. To change the version you can run the
set-version command:
The Maven
grails set-version 0.2
groupId will be the same as the project name, unless you specify a different one in Config.groovy:
PluginsWith a Grails plugin the
groupId and
version are taken from the following properties in the *GrailsPlugin.groovy descriptor:
The 'artifactId' is taken from the plugin name. For example if you have a plugin called
String groupId = 'myOrg' String version = '0.1'
FeedsGrailsPlugin the
artifactId will be "feeds". If your plugin does not specify a
groupId then this defaults to "org.grails.plugins".
3.7.10 Plugin DependenciesAs of Grails 1.3 you can declaratively specify plugins as dependencies via the dependency DSL instead of using the install-plugin command:
If you don't specify a group id the default plugin group id of
grails.project.dependency.resolution = { … repositories { … } plugins { runtime ':hibernate:1.2.1' } dependencies { … } … }
org.grails.plugins is used. You can specify to use the latest version of a particular plugin by using "latest.integration" as the version number:
plugins { runtime ':hibernate:latest.integration' }
Integration vs. ReleaseThe "latest.integration" version label will also include resolving snapshot versions. If you don't want to include snapshot versions then you can use the "latest.release" label:
plugins { runtime ':hibernate:latest.release' }
The "latest.release" label only works with Maven compatible repositories. If you have a regular SVN-based Grails repository then you should use "latest.integration".And of course if you are using a Maven repository with an alternative group id you can specify a group id:
plugins { runtime 'mycompany:hibernate:latest.integration' }
Plugin ExclusionsYou can control how plugins transitively resolves both plugin and JAR dependencies using exclusions. For example:
Here we have defined a dependency on the "weceem" plugin which transitively depends on the "searchable" plugin. By using the
plugins {
runtime( ':weceem:0.8' ) {
excludes "searchable"
excludes method you can tell Grails not to transitively install the searchable plugin. You can combine this technique to specify an alternative version of a plugin:
You can also completely disable transitive plugin installs, in which case no transitive dependencies will be resolved:
plugins {
runtime( ':weceem:0.8' ) {
excludes "searchable" // excludes most recent version
runtime ':searchable:0.5.4' // specifies a fixed searchable version
plugins {
runtime( ':weceem:0.8' ) {
transitive = false
runtime ':searchable:0.5.4' // specifies a fixed searchable version
4. The Command LineGrails' command line system is built on Gant - a simple Groovy wrapper around Apache Ant.However, Grails takes it a bit further through the use of convention and the
grails command. When you type:
Grails does a search in the following directories for Gant scripts to execute:
grails [command name]
Results in a search for the following files:
grails run-app
Which outputs usage instructions and the list of commands Grails is aware of:
grails help
Usage (optionals marked with *):
grails [environment]* [target] [arguments]*Examples:
grails dev run-app
grails create-app booksAvailable Targets (type grails help 'target-name' for more info):
grails bootstrap
grails bug-report
grails clean
grails compile
Refer to the Command Line reference in left menu of the reference guide for more information about individual commandsIt's often useful to provide custom arguments to the JVM when running Grails commands, in particular with
run-app where you may for example want to set a higher maximum heap size. The Grails command will use any JVM options provided in the general
JAVA_OPTS environment variable, but you can also specify a Grails-specific environment variable too:
export GRAILS_OPTS="-Xmx1G -Xms256m -XX:MaxPermSize=256m"
grails run-app
4.1 Creating Gant ScriptsYou can create your own Gant scripts by running the create-script command from the root of your project. For example the following command:
Will create a script called
grails create-script compile-sources
scripts/CompileSources.groovy. A Gant script itself is similar to a regular Groovy script except that it supports the concept of "targets" and dependencies between them:
As demonstrated in the script above, there is an implicit
target(default:"The default target is the one that gets executed by Grails") { depends(clean, compile) } target(clean:"Clean out things") { ant.delete(dir:"output") } target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }
ant variable that allows access to the Apache Ant API.
In previous versions of Grails (1.0.3 and below), the variable was You can also "depend" on other targets using the
Ant, i.e. with a capital first letter.
depends method demonstrated in the
default target above.
The default targetIn the example above, we specified a target with the explicit name "default". This is one way of defining the default target for a script. An alternative approach is to use the
setDefaultTarget() method:
This allows you to call the default target directly from other scripts if you wish. Also, although we have put the call to
target("clean-compile": "Performs a clean compilation on the app's source files.") { depends(clean, compile) } target(clean:"Clean out things") { ant.delete(dir:"output") } target(compile:"Compile some sources") { ant.mkdir(dir:"mkdir") ant.javac(srcdir:"src/java", destdir:"output") }setDefaultTarget("clean-compile")
setDefaultTarget() at the end of the script in this example, it can go anywhere as long as it comes after the target it refers to ("clean-compile" in this case).Which approach is better? To be honest, you can use whichever you prefer - there don't seem to be any major advantages in either case. One thing we would say is that if you want to allow other scripts to call your "default" target, you should move it into a shared script that doesn't have a default target at all. We'll talk some more about this in the next section.
4.2 Re-using Grails scriptsGrails ships with a lot of command line functionality out of the box that you may find useful in your own scripts (See the command line reference in the reference guide for info on all the commands). Of particular use are the compile, package and bootstrap scripts.The bootstrap script for example allows you to bootstrap a Spring ApplicationContext instance to get access to the data source and so on (the integration tests use this):
includeTargets << grailsScript("_GrailsBootstrap")target ('default': "Load the Grails interactive shell") { depends( configureProxy, packageApp, classpath, loadApp, configureApp ) Connection c try { // do something with connection c = appCtx.getBean('dataSource').getConnection() } finally { c?.close() } }
Pulling in targets from other scriptsGant allows you to pull in all targets (except "default") from another Gant script. You can then depend upon or invoke those targets as if they had been defined in the current script. The mechanism for doing this is the
includeTargets property. Simply "append" a file or class to it using the left-shift operator:
Don't worry too much about the syntax using a class, it's quite specialised. If you're interested, look into the Gant documentation.
includeTargets << new File("/path/to/my/script.groovy") includeTargets << gant.tools.Ivy
Core Grails targetsAs you saw in the example at the beginning of this section, you use neither the File- nor the class-based syntax for
includeTargets when including core Grails targets. Instead, you should use the special
grailsScript() method that is provided by the Grails command launcher (note that this is not available in normal Gant scripts, just Grails ones).The syntax for the
grailsScript() method is pretty straightforward: simply pass it the name of the Grails script you want to include, without any path information. Here is a list of Grails scripts that you may want to re-use:
|You really should include this! Fortunately, it is included automatically by all other Grails scripts bar one (_GrailsProxy), so you usually don't have to include it explicitly.
|If you want to fire events, you need to include this. Adds an
event(String eventName, List args) method. Again, included by almost all other Grails scripts.
|Sets up compilation, test, and runtime classpaths. If you want to use or play with them, include this script. Again, included by almost all other Grails scripts.
|If you want to access the internet, include this script so that you don't run into problems with proxies.
|Provides a
parseArguments target that does what it says on the tin: parses the arguments provided by the user when they run your script. Adds them to the
argsMap property.
|Contains all the shared test code. Useful if you want to add any extra tests.
|Provides all you need to run the application in the configured servlet container, either normally (
runAppHttps) or from a WAR file (
In pre-1.1 versions of Grails, the "_Grails..." scripts were not available. Instead, you typically include the corresponding command script, for example "Init.groovy" or "Bootstrap.groovy".Also, in pre-1.0.4 versions of Grails you cannot use the
grailsScript()method. Instead, you must use
includeTargets << new File(...)and specify the script's location in full (i.e. $GRAILS_HOME/scripts).
Script architectureYou maybe wondering what those underscores are doing in the names of the Grails scripts. That is Grails' way of determining that a script is internal , or in other words that it has not corresponding "command". So you can't run "grails _grails-settings" for example. That is also why they don't have a default target.Internal scripts are all about code sharing and re-use. In fact, we recommend you take a similar approach in your own scripts: put all your targets into an internal script that can be easily shared, and provide simple command scripts that parse any command line arguments and delegate to the targets in the internal script. Say you have a script that runs some functional tests - you can split it like this:
Here are a few general guidelines on writing scripts:
./scripts/FunctionalTests.groovy:includeTargets << new File("${basedir}/scripts/_FunctionalTests.groovy")target(default: "Runs the functional tests for this project.") { depends(runFunctionalTests) }./scripts/_FunctionalTests.groovy:includeTargets << grailsScript("_GrailsTest")target(runFunctionalTests: "Run functional tests.") { depends(...) … }
- Split scripts into a "command" script and an internal one.
- Put the bulk of the implementation in the internal script.
- Put argument parsing into the "command" script.
- To pass arguments to a target, create some script variables and initialise them before calling the target.
- Avoid name clashes by using closures assigned to script variables instead of targets. You can then pass arguments direct to the closures.
4.3 Hooking into EventsGrails provides the ability to hook into scripting events. These are events triggered during execution of Grails target and plugin scripts.The mechanism is deliberately simple and loosely specified. The list of possible events is not fixed in any way, so it is possible to hook into events triggered by plugin scripts, for which there is no equivalent event in the core target scripts.
Defining event handlersEvent handlers are defined in scripts called
_Events.groovy. Grails searches for these scripts in the following locations:
USER_HOME/.grails/scripts- user-specific event handlers
PROJECT_HOME/scripts- applicaton-specific event handlers
PLUGINS_HOME/*/scripts- plugin-specific event handlers
GLOBAL_PLUGINS_HOME/*/scripts- event handlers provided by global plugins
_Events.groovy file.
In versions of Grails prior to 1.0.4, the script was called Event handlers are blocks defined in
Events.groovy, that is without the leading underscore.
_Events.groovy, with a name beginning with "event". The following example can be put in your /scripts directory to demonstrate the feature:
You can see here the three handlers
eventCreatedArtefact = { type, name ->
println "Created $type $name"
}eventStatusUpdate = { msg ->
println msg
}eventStatusFinal = { msg ->
println msg
eventStatusFinal. Grails provides some standard events, which are documented in the command line reference guide. For example the compile command fires the following events:
CompileStart- Called when compilation starts, passing the kind of compile - source or tests
CompileEnd- Called when compilation is finished, passing the kind of compile - source or tests
Triggering eventsTo trigger an event simply include the Init.groovy script and call the event() closure:
includeTargets << grailsScript("_GrailsEvents")event("StatusFinal", ["Super duper plugin action complete!"])
Common EventsBelow is a table of some of the common events that can be leveraged:
|Passed a string indicating current script status/progress
|Passed a string indicating an error message from the current script
|Passed a string indicating the final script status message, i.e. when completing a target, even if the target does not exit the scripting environment
|Called when a create-xxxx script has completed and created an artefact
|Called whenever a project source filed is created, not including files constantly managed by Grails
|Called when the scripting environment is about to exit cleanly
|Called after a plugin has been installed
|Called when compilation starts, passing the kind of compile - source or tests
|Called when compilation is finished, passing the kind of compile - source or tests
|Called when documentation generation is about to start - javadoc or groovydoc
|Called when documentation generation has ended - javadoc or groovydoc
|Called during classpath initialization so plugins can augment the classpath with rootLoader.addURL(...). Note that this augments the classpath after event scripts are loaded so you cannot use this to load a class that your event script needs to import, although you can do this if you load the class by name.
|Called at the end of packaging (which is called prior to the Tomcat server being started and after web.xml is generated)
4.4 Customising the buildGrails is most definitely an opinionated framework and it prefers convention to configuration, but this doesn't mean you can't configure it. In this section, we look at how you can influence and modify the standard Grails build.
The defaultsIn order to customise a build, you first need to know what you can customise. The core of the Grails build configuration is the
grails.util.BuildSettings class, which contains quite a bit of useful information. It controls where classes are compiled to, what dependencies the application has, and other such settings.Here is a selection of the configuration options and their default values:
|Config option
|Default value
BuildSettings class has some other properties too, but they should be treated as read-only:
|The location of the project.
|The user's home directory.
|The location of the Grails installation in use (may be null).
|The version of Grails being used by the project.
|The current Grails environment.
|A list of compile-time project dependencies as
File instances.
|A list of test-time project dependencies as
File instances.
|A list of runtime-time project dependencies as
File instances.
BuildSettings is available to your scripts via the
grailsSettings script variable. You can also access it from your code by using the
grails.util.BuildSettingsHolder class, but this isn't recommended.
Overriding the defaultsAll of the properties in the first table can be overridden by a system property or a configuration option - simply use the "config option" name. For example, to change the project working directory, you could either run this command:
or add this option to your
grails -Dgrails.project.work.dir=work compile
grails-app/conf/BuildConfig.groovy file:
Note that the default values take account of the property values they depend on, so setting the project working directory like this would also relocate the compiled classes, test classes, resources, and plugins.What happens if you use both a system property and a configuration option? Then the system property wins because it takes precedence over the
grails.project.work.dir = "work"
BuildConfig.groovy file, which in turn takes precedence over the default values.The
BuildConfig.groovy file is a sibling of
grails-app/conf/Config.groovy - the former contains options that only affect the build, whereas the latter contains those that affect the application at runtime. It's not limited to the options in the first table either: you will find build configuration options dotted around the documentation, such as ones for specifying the port that the embedded servlet container runs on or for determining what files get packaged in the WAR file.
Available build settings
|Port to run the embedded servlet container on ("run-app" and "run-war"). Integer.
|Port to run the embedded servlet container on for HTTPS ("run-app --https" and "run-war --https"). Integer.
|Path to a custom web.xml file to use for the application (alternative to using the web.xml template).
|Legacy approach to adding extra dependencies to the compiler classpath. Set it to a closure containing "fileset()" entries. These entries will be processed by an
AntBuilder so the syntax is the Groovy form of the corresponding XML elements in an Ant build file, e.g.
fileset(dir: "$basedir/lib", include: "**/*.class).
|A list of Ant path patterns that allow you to control which files are included in the tests. The patterns should not include the test case suffix, which is set by the next property.
|By default, tests are assumed to have a suffix of "Tests". You can change it to anything you like but setting this option. For example, another common suffix is "Test".
|A string containing the file path of the generated WAR file, along with its full name (include extension). For example, "target/my-app.war".
|A closure containing "fileset()" entries that allows you complete control over what goes in the WAR's "WEB-INF/lib" directory.
|A closure containing "fileset()" entries that allows you complete control over what goes in the root of the WAR. It overrides the default behaviour of including everything under "web-app".
|A closure that takes the location of the staging directory as its first argument. You can use any Ant tasks to do anything you like. It is typically used to remove files from the staging directory before that directory is jar'd up into a WAR.
|The location to generate Grails' web.xml to
4.5 Ant and MavenIf all the other projects in your team or company are built using a standard build tool such as Ant or Maven, you become the black sheep of the family when you use the Grails command line to build your application. Fortunately, you can easily integrate the Grails build system into the main build tools in use today (well, the ones in use in Java projects at least).
Ant IntegrationWhen you create a Grails application via the create-app command, Grails automatically creates an Apache Ant
build.xml file for you containing the following targets:
clean- Cleans the Grails application
compile- Compiles your application's source code
test- Runs the unit tests
run- Equivalent to "grails run-app"
war- Creates a WAR file
deploy- Empty by default, but can be used to implement automatic deployment
The build file is all geared up to use Apache Ivy for dependency management, which means that it will automatically download all the requisite Grails JAR files and other dependencies on demand. You don't even have to install Grails locally to use it! That makes it particularly useful for continuous integration systems such as CruiseControl or HudsonIt uses the Grails Ant task to hook into the existing Grails build system. The task allows you to run any Grails script that's available, not just the ones used by the generated build file. To use the task, you must first declare it:
ant war
This raises the question: what should be in "grails.classpath"? The task itself is in the "grails-bootstrap" JAR artifact, so that needs to be on the classpath at least. You should also include the "groovy-all" JAR. With the task defined, you just need to use it! The following table shows you what attributes are available:
<taskdef name="grailsTask" classname="grails.ant.GrailsTask" classpathref="grails.classpath"/>
|The location of the Grails installation directory to use for the build.
|Yes, unless classpath is specified.
|Classpath to load Grails from. Must include the "grails-bootstrap" artifact and should include "grails-scripts".
|Yes, unless
home is set or you use a
classpath element.
|The name of the Grails script to run, e.g. "TestApp".
|The arguments to pass to the script, e.g. "-unit -xml".
|No. Defaults to "".
|The Grails environment to run the script in.
|No. Defaults to the script default.
|Advanced setting: adds the application's runtime classpath to the build classpath if true.
|No. Defaults to true.
classpath- The build classpath (used to load Gant and the Grails scripts).
compileClasspath- Classpath used to compile the application's classes.
runtimeClasspath- Classpath used to run the application and package the WAR. Typically includes everything in @compileClasspath.
testClasspath- Classpath used to compile and run the tests. Typically includes everything in
home attribute and put your own dependencies in the
lib directory, then you don't even need to use any of them. For an example of their use, take a look at the generated Ant build file for new apps.
Maven IntegrationFrom 1.1 onwards, Grails provides integration with Maven 2 via a Maven plugin. The current Maven plugin is based on, but effectively supersedes, the version created by Octo, who did a great job.
PreparationIn order to use the new plugin, all you need is Maven 2 installed and set up. This is because you no longer need to install Grails separately to use it with Maven!
The Maven 2 integration for Grails has been designed and tested for Maven 2.0.9 and above. It will not work with earlier versions.
The default mvn setup DOES NOT supply sufficient memory to run the Grails environment. We recommend that you add the following environment variable setting to prevent poor performance:
export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=192m"
Creating a Grails Maven ProjectTo create a Mavenized Grails project simply run the following command:
Choose whichever grails version, group ID and artifact ID you want for your application, but everything else must be as written. This will create a new Maven project with a POM and a couple of other files. What you won't see is anything that looks like a Grails application. So, the next step is to create the project structure that you're used to. But first, if you want to set target JDK to Java 6, do that now. Open my-app/pom.xml and change
mvn archetype:generate -DarchetypeGroupId=org.grails \ -DarchetypeArtifactId=grails-maven-archetype \ -DarchetypeVersion=1.3.2 \ -DgroupId=example -DartifactId=my-app
<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin>
Then you're ready to create the project structure:
<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin>
cd my-app mvn initialize
if you see a message similar to this:Now you have a Grails application all ready to go. The plugin integrates into the standard build cycle, so you can use the standard Maven phases to build and package your app:you need to add the plugins manually to application.properties:Resolving plugin JAR dependencies … :: problems summary :: :::: WARNINGS module not found: org.hibernate#hibernate-core;3.3.1.GAthen runplugins.hibernate=1.3.2 plugins.tomcat=1.3.2and the hibernate and tomcat plugins will be installed.mvn compile
mvn clean ,
mvn compile ,
mvn test ,
mvn package ,
mvn install .You can also take advantage of some of the Grails commands that have been wrapped as Maven goals:
grails:create-controller- Calls the create-controller command
grails:create-domain-class- Calls the create-domain-class command
grails:create-integration-test- Calls the create-integration-test command
grails:create-pom- Creates a new Maven POM for an existing Grails project
grails:create-script- Calls the create-script command
grails:create-service- Calls the create-service command
grails:create-taglib- Calls the create-tag-lib command
grails:create-unit-test- Calls the create-unit-test command
grails:exec- Executes an arbitrary Grails command line script
grails:generate-all- Calls the generate-all command
grails:generate-controller- Calls the generate-controller command
grails:generate-views- Calls the generate-views command
grails:install-plugin- Calls the install-plugin command
grails:install-templates- Calls the install-templates command
grails:list-plugins- Calls the list-plugins command
grails:package- Calls the package command
grails:run-app- Calls the run-app command
grails:uninstall-plugin- Calls the uninstall-plugin command
mvn grails:help
Mavenizing an existing projectCreating a new project is great way to start, but what if you already have one? You don't want to create a new project and then copy the contents of the old one over. The solution is to create a POM for the existing project using this Maven command (substitute the version number with the grails version of your existing project):
When this command has finished, you can immediately start using the standard phases, such as
mvn org.grails:grails-maven-plugin:1.3.2:create-pom -DgroupId=com.mycompany
mvn package. Note that you have to specify a group ID when creating the POM.You may also want to set target JDK to Java 6, see above.
Adding Grails commands to phasesThe standard POM created for you by Grails already attaches the appropriate core Grails commands to their corresponding build phases, so "compile" goes in the "compile" phase and "war" goes in the "package" phase. That doesn't help though when you want to attach a plugin's command to a particular phase. The classic example is functional tests. How do you make sure that your functional tests (using which ever plugin you have decided on) are run during the "integration-test" phase?Fear not: all things are possible. In this case, you can associate the command to a phase using an extra "execution" block:
This also demonstrates the
<plugin> <groupId>org.grails</groupId> <artifactId>grails-maven-plugin</artifactId> <version>1.3.2</version> <extensions>true</extensions> <executions> <execution> <goals> … </goals> </execution> <!-- Add the "functional-tests" command to the "integration-test" phase --> <execution> <id>functional-tests</id> <phase>integration-test</phase> <goals> <goal>exec</goal> </goals> <configuration> <command>functional-tests</command> </configuration> </execution> </executions> </plugin>
grails:exec goal, which can be used to run any Grails command. Simply pass the name of the command as the
command system property, and optionally specify the arguments via the
args property:
mvn grails:exec -Dcommand=create-webtest -Dargs=Book
Debugging a Grails Maven ProjectMaven can be launched in debug mode using the "mvnDebug" command. To launch your Grails application in debug, simply run:
The process will be suspended on startup and listening for a debugger on port 8000.If you need more control of the debugger, this can be specified using the MAVEN_OPTS environment variable, and launch Maven via the default "mvn" command:
mvnDebug grails:run-app
MAVEN_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
mvn grails:run-app
Raising issuesIf you come across any problems with the Maven integration, please raise a JIRA issue as a sub-task of GRAILS-3547.
5. Object Relational Mapping (GORM)Domain classes are core to any business application. They hold state about business processes and hopefully also implement behavior. They are linked together through relationships, either one-to-one or one-to-many.GORM is Grails' object relational mapping (ORM) implementation. Under the hood it uses Hibernate 3 (an extremely popular and flexible open source ORM solution) but because of the dynamic nature of Groovy, the fact that it supports both static and dynamic typing, and the convention of Grails there is less configuration involved in creating Grails domain classes.You can also write Grails domain classes in Java. See the section on Hibernate Integration for how to write Grails domain classes in Java but still use dynamic persistent methods. Below is a preview of GORM in action:
def book = Book.findByTitle("Groovy in Action")book .addToAuthors(name:"Dierk Koenig") .addToAuthors(name:"Guillaume LaForge") .save()
5.1 Quick Start GuideA domain class can be created with the create-domain-class command:
This will create a class at the location
grails create-domain-class Person
grails-app/domain/Person.groovy such as the one below:
class Person { }
If you have the You can customize the class by adding properties:
dbCreate property set to "update", "create" or "create-drop" on your DataSource, Grails will automatically generated/modify the database tables for you.
Once you have a domain class try and manipulate it via the shell or console by typing:
class Person { String name Integer age Date lastVisit }
This loads an interactive GUI where you can type Groovy commands.
grails console
5.1.1 Basic CRUDTry performing some basic CRUD (Create/Read/Update/Delete) operations.
CreateTo create a domain class use the Groovy new operator, set its properties and call save:
The save method will persist your class to the database using the underlying Hibernate ORM layer.
def p = new Person(name:"Fred", age:40, lastVisit:new Date()) p.save()
ReadGrails transparently adds an implicit
id property to your domain class which you can use for retrieval:
This uses the get method that expects a database identifier to read the
def p = Person.get(1) assert 1 == p.id
Person object back from the db.
You can also load an object in a read-only state by using the read method:
In this case the underlying Hibernate engine will not do any dirty checking and the object will not be persisted. Note that if you explicitly call the save method then the object is placed back into a read-write state.In addition, you can also load an proxy for an instance by using the load method:
def p = Person.read(1)
This incurs no database access until a method other than getId() is called. Hibernate then initializes the proxied instance, or throws an exception if no record is found for the specified id.
def p = Person.load(1)
UpdateTo update an instance, set some properties and then simply call save again:
def p = Person.get(1)
p.name = "Bob"
DeleteTo delete an instance use the delete method:
def p = Person.get(1) p.delete()
5.2 Domain Modelling in GORMWhen building Grails applications you have to consider the problem domain you are trying to solve. For example if you were building an Amazon bookstore you would be thinking about books, authors, customers and publishers to name a few.These are modeled in GORM as Groovy classes so a
Book class may have a title, a release date, an ISBN number and so on. The next few sections show how to model the domain in GORM.To create a domain class you can run the create-domain-class target as follows:
The result will be a class at
grails create-domain-class Book
class Book { }
If you wish to use packages you can move the Book.groovy class into a sub directory under the domain directory and add the appropriate The above class will map automatically to a table in the database called
package declaration as per Groovy (and Java's) packaging rules.
book (the same name as the class). This behaviour is customizable through the ORM Domain Specific LanguageNow that you have a domain class you can define its properties as Java types. For example:
Each property is mapped to a column in the database, where the convention for column names is all lower case separated by underscores. For example
class Book { String title Date releaseDate String ISBN }
releaseDate maps onto a column
release_date. The SQL types are auto-detected from the Java types, but can be customized via Constraints or the ORM DSL.
5.2.1 Association in GORMRelationships define how domain classes interact with each other. Unless specified explicitly at both ends, a relationship exists only in the direction it is defined.
18.104.22.168 Many-to-one and one-to-oneA many-to-one relationship is the simplest kind, and is defined trivially using a property of the type of another domain class. Consider this example:
Example A
In this case we have a unidirectional many-to-one relationship from
class Face { Nose nose } class Nose { }
Face to
Nose. To make this relationship bidirectional define the other side as follows:
Example B
In this case we use the
class Face {
Nose nose
class Nose {
static belongsTo = [face:Face]
belongsTo setting to say that
Nose "belongs to"
Face. The result of this is that we can create a
Face, attach a
Nose instance to it and when we save or delete the
Face instance, GORM will save or delete the
Nose. In other words, saves and deletes will cascade from
Face to the associated
The example above will save both face and nose. Note that the inverse is not true and will result in an error due to a transient
new Face(nose:new Nose()).save()
Now if we delete the
new Nose(face:new Face()).save() // will cause an error
Face instance, the
Nose will go to:
To make the relationship a true one-to-one, use the
def f = Face.get(1) f.delete() // both Face and Nose deleted
hasOne property on the owning side, e.g.
Example C
Note that using this property puts the foreign key on the inverse table to the previous example, so in this case the foreign key column is stored in the
class Face {
static hasOne = [nose:Nose]
class Nose {
Face face
nose table inside a column called
face_id. Also,
hasOne only works with bidirectional relationships.Finally, it's a good idea to add a unique constraint on one side of the one-to-one relationship:
class Face { static hasOne = [nose:Nose] static constraints = { nose unique: true } }class Nose { Face face }
220.127.116.11 One-to-manyA one-to-many relationship is when one class, example
Author, has many instances of a another class, example
Book. With Grails you define such a relationship with the
hasMany setting:
In this case we have a unidirectional one-to-many. Grails will, by default, map this kind of relationship with a join table.
class Author { static hasMany = [ books : Book ] String name } class Book { String title }
The ORM DSL allows mapping unidirectional relationships using a foreign key association insteadGrails will automatically inject a property of type
java.util.Set into the domain class based on the
hasMany setting. This can be used to iterate over the collection:
def a = Author.get(1)a.books.each { println it.title }
The default fetch strategy used by Grails is "lazy", which means that the collection will be lazily initialized. This can lead to the n+1 problem if you are not careful.If you need "eager" fetching you can use the ORM DSL or specify eager fetching as part of a queryThe default cascading behaviour is to cascade saves and updates, but not deletes unless a
belongsTo is also specified:
If you have two properties of the same type on the many side of a one-to-many you have to use
class Author { static hasMany = [ books : Book ] String name } class Book { static belongsTo = [author:Author] String title }
mappedBy to specify which the collection is mapped:
This is also true if you have multiple collections that map to different properties on the many side:
class Airport { static hasMany = [flights:Flight] static mappedBy = [flights:"departureAirport"] } class Flight { Airport departureAirport Airport destinationAirport }
class Airport { static hasMany = [outboundFlights:Flight, inboundFlights:Flight] static mappedBy = [outboundFlights:"departureAirport", inboundFlights:"destinationAirport"] } class Flight { Airport departureAirport Airport destinationAirport }
184.108.40.206 Many-to-manyGrails supports many-to-many relationships by defining a
hasMany on both sides of the relationship and having a
belongsTo on the owned side of the relationship:
Grails maps a many-to-many using a join table at the database level. The owning side of the relationship, in this case
class Book { static belongsTo = Author static hasMany = [authors:Author] String title } class Author { static hasMany = [books:Book] String name }
Author, takes responsibility for persisting the relationship and is the only side that can cascade saves across.For example this will work and cascade saves:
However the below will only save the
new Author(name:"Stephen King") .addToBooks(new Book(title:"The Stand")) .addToBooks(new Book(title:"The Shining")) .save()
Book and not the authors!
This is the expected behaviour as, just like Hibernate, only one side of a many-to-many can take responsibility for managing the relationship.
new Book(name:"Groovy in Action") .addToAuthors(new Author(name:"Dierk Koenig")) .addToAuthors(new Author(name:"Guillaume Laforge")) .save()
Grails' Scaffolding feature does not currently support many-to-many relationship and hence you must write the code to manage the relationship yourself
184.108.40.206 Basic Collection TypesAs well as associations between different domain classes, GORM also supports mapping of basic collection types. For example, the following class creates a
nicknames association that is a
Set of
String instances:
GORM will map an association like the above using a join table. You can alter various aspects of how the join table is mapped using the
class Person { static hasMany = [nicknames:String] }
joinTable argument:
The example above will map to a table that looks like the following:bunch_o_nicknames Table
class Person { static hasMany = [nicknames:String] static mapping = { hasMany joinTable: [name: 'bunch_o_nicknames', key: 'person_id', column: 'nickname', type: "text"] } }
--------------------------------------------- | person_id | nickname | --------------------------------------------- | 1 | Fred | ---------------------------------------------
5.2.2 Composition in GORMAs well as association, Grails supports the notion of composition. In this case instead of mapping classes onto separate tables a class can be "embedded" within the current table. For example:
The resulting mapping would looking like this:
class Person { Address homeAddress Address workAddress static embedded = ['homeAddress', 'workAddress'] } class Address { String number String code }
If you define the
Addressclass in a separate Groovy file in the
grails-app/domaindirectory you will also get an
addresstable. If you don't want this to happen use Groovy's ability to define multiple classes per file and include the
Addressclass below the
Personclass in the
5.2.3 Inheritance in GORMGORM supports inheritance both from abstract base classes and concrete persistent GORM entities. For example:
In the above example we have a parent
class Content { String author } class BlogEntry extends Content { URL url } class Book extends Content { String ISBN } class PodCast extends Content { byte[] audioStream }
Content class and then various child classes with more specific behaviour.
ConsiderationsAt the database level Grails by default uses table-per-hierarchy mapping with a discriminator column called
class so the parent class (
Content) and its sub classes (
Book etc.), share the same table.Table-per-hierarchy mapping has a down side in that you cannot have non-nullable properties with inheritance mapping. An alternative is to use table-per-subclass which can be enabled via the ORM DSLHowever, excessive use of inheritance and table-per-subclass can result in poor query performance due to the excessive use of join queries. In general our advice is if you're going to use inheritance, don't abuse it and don't make your inheritance hierarchy too deep.
Polymorphic QueriesThe upshot of inheritance is that you get the ability to polymorphically query. For example using the list method on the
Content super class will return all sub classes of
def content = Content.list() // list all blog entries, books and pod casts content = Content.findAllByAuthor('Joe Bloggs') // find all by authordef podCasts = PodCast.list() // list only pod casts
5.2.4 Sets, Lists and Maps
Sets of objectsBy default when you define a relationship with GORM it is a
java.util.Set which is an unordered collection that cannot contain duplicates. In other words when you have:
The books property that GORM injects is a
class Author {
static hasMany = [books:Book]
java.util.Set. The problem with this is there is no ordering when accessing the collection, which may not be what you want. To get custom ordering you can say that the set is a
In this case a
class Author {
SortedSet books
static hasMany = [books:Book]
java.util.SortedSet implementation is used which means you have to implement
java.lang.Comparable in your Book class:
The result of the above class is that the Book instances in the books collections of the Author class will be ordered by their release date.
class Book implements Comparable { String title Date releaseDate = new Date() int compareTo(obj) { releaseDate.compareTo(obj.releaseDate) } }
Lists of objectsIf you simply want to be able to keep objects in the order which they were added and to be able to reference them by index like an array you can define your collection type as a
In this case when you add new elements to the books collection the order is retained in a sequential list indexed from 0 so you can do:
class Author {
List books
static hasMany = [books:Book]
The way this works at the database level is Hibernate creates a
author.books[0] // get the first book
books_idx column where it saves the index of the elements in the collection in order to retain this order at the db level.When using a
List, elements must be added to the collection before being saved, otherwise Hibernate will throw an exception (
org.hibernate.HibernateException: null index column for collection):
// This won't work! def book = new Book(title: 'The Shining') book.save() author.addToBooks(book)// Do it this way instead. def book = new Book(title: 'Misery') author.addToBooks(book) author.save()
Maps of ObjectsIf you want a simple map of string/value pairs GORM can map this with the following:
In this case the key and value of the map MUST be strings.If you want a Map of objects then you can do this:
class Author { Map books // map of ISBN:book names }def a = new Author() a.books = ["1590597583":"Grails Book"] a.save()
The static
class Book { Map authors static hasMany = [authors:Author] }def a = new Author(name:"Stephen King")def book = new Book() book.authors = [stephen:a] book.save()
hasMany property defines the type of the elements within the Map. The keys for the map must be strings.
A Note on Collection Types and PerformanceThe Java
Set type is a collection that doesn't allow duplicates. In order to ensure uniqueness when adding an entry to a
Set association Hibernate has to load the entire associations from the database. If you have a large numbers of entries in the association this can be costly in terms of performance.The same behavior is required for
List types, since Hibernate needs to load the entire association in-order to maintain order. Therefore it is recommended that if you anticipate a large numbers of records in the association that you make the association bidirectional so that the link can be created on the inverse side. For example consider the following code:
In this example the association link is being created by the child (Book) and hence it is not necessary to manipulate the collection directly resulting in fewer queries and more efficient code. Given an
def book = new Book(title:"New Grails Book") def author = Author.get(1) book.author = author book.save()
Author with a large number of associated
Book instances if you were to write code like the following you would see an impact on performance:
def book = new Book(title:"New Grails Book") def author = Author.get(1) author.addToBooks(book) author.save()
5.3 Persistence BasicsA key thing to remember about Grails is that under the surface Grails is using Hibernate for persistence. If you are coming from a background of using ActiveRecord or iBatis Hibernate's "session" model may feel a little strange.Essentially, Grails automatically binds a Hibernate session to the currently executing request. This allows you to use the save and delete methods as well as other GORM methods transparently.
5.3.1 Saving and UpdatingAn example of using the save method can be seen below:
A major difference with Hibernate is when you call save it does not necessarily perform any SQL operations at that point. Hibernate typically batches up SQL statements and executes them at the end. This is typically done for you automatically by Grails, which manages your Hibernate session.There are occasions, however, when you may want to control when those statements are executed or, in Hibernate terminology, when the session is "flushed". To do so you can use the flush argument to the save method:
def p = Person.get(1) p.save()
Note that in this case all pending SQL statements including previous saves will be synchronized with the db. This also allows you to catch any exceptions thrown, which is typically useful in highly concurrent scenarios involving optimistic locking:
def p = Person.get(1)
You can find out more about the subtleties of saving data in this article - a must read!
def p = Person.get(1) try { p.save(flush:true) } catch(Exception e) { // deal with exception }
5.3.2 Deleting ObjectsAn example of the delete method can be seen below:
By default Grails will use transactional write behind to perform the delete, if you want to perform the delete in place then you can use the
def p = Person.get(1) p.delete()
flush argument:
Using the
def p = Person.get(1)
flush argument will also allow you to catch any errors that may potentially occur during a delete. A common error that may occur is if you violate a database constraint, although this is normally down to a programming or schema error. The following example shows how to catch a
DataIntegrityViolationException that is thrown when you violate the database constraints:
Note that Grails does not supply a
def p = Person.get(1)try { p.delete(flush:true) } catch(org.springframework.dao.DataIntegrityViolationException e) { flash.message = "Could not delete person ${p.name}" redirect(action:"show", id:p.id) }
deleteAll method as deleting data is discouraged and can often be avoided through boolean flags/logic.If you really need to batch delete data you can use the executeUpdate method to do batch DML statements:
Customer.executeUpdate("delete Customer c where c.name = :oldName", [oldName:"Fred"])
5.3.3 Understanding Cascading Updates and DeletesIt is critical that you understand how cascading updates and deletes work when using GORM. The key part to remember is the
belongsTo setting which controls which class "owns" a relationship.Whether it is a one-to-one, one-to-many or many-to-many, defining
belongsTo will result in updates cascading from the owning class to its dependant (the other side of the relationship), and for many-/one-to-one and one-to-many relationships deletes will also cascade.If you do not define
belongsTo then no cascades will happen and you will have to manually save each object (except in the case of the one-to-many, in which case saves will cascade automatically if a new instance is in a
hasMany collection).Here is an example:
If I now create an
class Airport { String name static hasMany = [flights:Flight] }class Flight { String number static belongsTo = [airport:Airport] }
Airport and add some
Flights to it I can save the
Airport and have the updates cascaded down to each flight, hence saving the whole object graph:
Conversely if I later delete the
new Airport(name:"Gatwick") .addToFlights(new Flight(number:"BA3430")) .addToFlights(new Flight(number:"EZ0938")) .save()
Airport all
Flights associated with it will also be deleted:
However, if I were to remove
def airport = Airport.findByName("Gatwick")
belongsTo then the above cascading deletion code would not work. To understand this better take a look at the summaries below that describe the default behaviour of GORM with regards to specific associations. Also read part 2 of the GORM Gotchas series of articles to get a deeper understanding of relationships and cascading.
Bidirectional one-to-many with belongsTo
In the case of a bidirectional one-to-many where the many side defines a
class A { static hasMany = [bees:B] } class B { static belongsTo = [a:A] }
belongsTo then the cascade strategy is set to "ALL" for the one side and "NONE" for the many side.
Unidirectional one-to-many
In the case of a unidirectional one-to-many where the many side defines no belongsTo then the cascade strategy is set to "SAVE-UPDATE".
class A { static hasMany = [bees:B] }
class B { }
Bidirectional one-to-many, no belongsTo
In the case of a bidirectional one-to-many where the many side does not define a
class A { static hasMany = [bees:B] }
class B { A a }
belongsTo then the cascade strategy is set to "SAVE-UPDATE" for the one side and "NONE" for the many side.
Unidirectional one-to-one with belongsTo
In the case of a unidirectional one-to-one association that defines a
class A { }
class B { static belongsTo = [a:A] }
belongsTo then the cascade strategy is set to "ALL" for the owning side of the relationship (A->B) and "NONE" from the side that defines the
belongsTo (B->A)Note that if you need further control over cascading behaviour, you can use the ORM DSL.
5.3.4 Eager and Lazy FetchingAssociations in GORM are by default lazy. This is best explained by example:
Given the above domain classes and the following code:
class Airport { String name static hasMany = [flights:Flight] } class Flight { String number Location destination static belongsTo = [airport:Airport] } class Location { String city String country }
GORM will execute a single SQL query to fetch the
def airport = Airport.findByName("Gatwick")
airport.flights.each {
println it.destination.city
Airport instance, another to get its flights, and then 1 extra query for each iteration over the
flights association to get the current flight's destination. In other words you get N+1 queries (if you exclude the original one to get the airport).
Configuring Eager FetchingAn alternative approach that avoids the N+1 queries is to use eager fetching, which can be specified as follows:
In this case the
class Airport { String name static hasMany = [flights:Flight] static mapping = { flights lazy: false } }
flights association will be loaded at the same time as its
Airport instance, although a second query will be executed to fetch the collection. You can also use
fetch: 'join' instead of
lazy: false , in which case GORM will only execute a single query to get the airports and their flights. This works well for single-ended associations, but you need to be careful with one-to-manys. Queries will work as you'd expect right up to the moment you add a limit to the number of results you want. At that point, you will likely end up with fewer results than you were expecting. The reason for this is quite technical but ultimately the problem arises from GORM using a left outer join.So, the recommendation is currently to use
fetch: 'join' for single-ended associations and
lazy: false for one-to-manys.Be careful how and where you use eager loading because you could load your entire database into memory with too many eager associations. You can find more information on the mapping options in the section on the ORM DSL.
Using Batch FetchingAlthough eager fetching is appropriate for some cases, it is not always desirable. If you made everything eager you could quite possibly load your entire database into memory resulting in performance and memory problems. An alternative to eager fetching is to use batch fetching. Essentially, you can configure Hibernate to lazily fetch results in "batches". For example:
In this case, due to the
class Airport { String name static hasMany = [flights:Flight] static mapping = { flights batchSize:10 } }
batchSize argument, when you iterate over the
flights association, Hibernate will fetch results in batches of 10. For example if you had an
Airport that had 30 flights, if you didn't configure batch fetching you would get 1 query to fetch the
Airport and then
30 queries to fetch each flight. With batch fetching you get 1 query to fetch the
Airport and 3 queries to fetch each
Flight in batches of 10. In other words, batch fetching is an optimization of the lazy fetching strategy. Batch fetching can also be configured at the class level as follows:
Check out part 3 of the GORM Gotchas series for more in-depth coverage of this tricky topic.
class Flight {
static mapping = {
batchSize 10
5.3.5 Pessimistic and Optimistic Locking
Optimistic LockingBy default GORM classes are configured for optimistic locking. Optimistic locking essentially is a feature of Hibernate which involves storing a version number in a special
version column in the database.The
version column gets read into a
version property that contains the current versioned state of persistent instance which you can access:
When you perform updates Hibernate will automatically check the version property against the version column in the database and if they differ will throw a StaleObjectException and the transaction will be rolled back.This is useful as it allows a certain level of atomicity without resorting to pessimistic locking that has an inherit performance penalty. The downside is that you have to deal with this exception if you have highly concurrent writes. This requires flushing the session:
def airport = Airport.get(10)println airport.version
The way you deal with the exception depends on the application. You could attempt a programmatic merge of the data or go back to the user and ask them to resolve the conflict.Alternatively, if it becomes a problem you can resort to pessimistic locking.
def airport = Airport.get(10)try { airport.name = "Heathrow" airport.save(flush:true) } catch(org.springframework.dao.OptimisticLockingFailureException e) { // deal with exception }
Pessimistic LockingPessimistic locking is equivalent to doing a SQL "SELECT * FOR UPDATE" statement and locking a row in the database. This has the implication that other read operations will be blocking until the lock is released.In Grails pessimistic locking is performed on an existing instance via the lock method:
Grails will automatically deal with releasing the lock for you once the transaction has been committed. However, in the above case what we are doing is "upgrading" from a regular SELECT to a SELECT..FOR UPDATE and another thread could still have updated the record in between the call to get() and the call to lock().To get around this problem you can use the static lock method that takes an id just like get:
def airport = Airport.get(10) airport.lock() // lock for update airport.name = "Heathrow" airport.save()
In this case only SELECT..FOR UPDATE is issued.
def airport = Airport.lock(10) // lock for update airport.name = "Heathrow" airport.save()
Though Grails, through Hibernate, supports pessimistic locking, the embedded HSQLDB shipped with Grails which is used as the default in-memory database does not. If you need to test pessimistic locking you will need to do so against a database that does have support such as MySQL.As well as the lock method you can also obtain a pessimistic locking using queries. For example using a dynamic finder:
Or using criteria:
def airport = Airport.findByName("Heathrow", [lock:true])
def airport = Airport.createCriteria().get {
eq('name', 'Heathrow')
lock true
5.3.6 Modification CheckingOnce you have loaded and possibly modified a persistent domain class instance, it isn't straightforward to retrieve the original values. If you try to reload the instance using get Hibernate will return the current modified instance from its Session cache. Reloading using another query would trigger a flush which could cause problems if your data isn't ready to be flushed yet. So GORM provides some methods to retrieve the original values that Hibernate caches when it loads the instance (which it uses for dirty checking).
isDirtyYou can use the isDirty method to check if any field has been modified:
You can also check if individual fields have been modified:
def airport = Airport.get(10) assert !airport.isDirty()airport.properties = params if (airport.isDirty()) { // do something based on changed state }
def airport = Airport.get(10) assert !airport.isDirty()airport.properties = params if (airport.isDirty('name')) { // do something based on changed name }
getDirtyPropertyNamesYou can use the getDirtyPropertyNames method to retrieve the names of modified fields; this may be empty but will not be null:
def airport = Airport.get(10) assert !airport.isDirty()airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { // do something based on changed value }
getPersistentValueYou can use the getPersistentValue method to retrieve the value of a modified field:
def airport = Airport.get(10) assert !airport.isDirty()airport.properties = params def modifiedFieldNames = airport.getDirtyPropertyNames() for (fieldName in modifiedFieldNames) { def currentValue = airport."$fieldName" def originalValue = airport.getPersistentValue(fieldName) if (currentValue != originalValue) { // do something based on changed value } }
5.4 Querying with GORMGORM supports a number of powerful ways to query from dynamic finders, to criteria to Hibernate's object oriented query language HQL.Groovy's ability to manipulate collections via GPath and methods like sort, findAll and so on combined with GORM results in a powerful combination.However, let's start with the basics.
Listing instancesIf you simply need to obtain all the instances of a given class you can use the list method:
The list method supports arguments to perform pagination:
def books = Book.list()
as well as sorting:
def books = Book.list(offset:10, max:20)
Here, the
def books = Book.list(sort:"title", order:"asc")
sort argument is the name of the domain class property that you wish to sort on, and the
order argument is either
asc for ascending or
desc for descending.
Retrieval by Database IdentifierThe second basic form of retrieval is by database identifier using the get method:
You can also obtain a list of instances for a set of identifiers using getAll:
def book = Book.get(23)
def books = Book.getAll(23, 93, 81)
5.4.1 Dynamic FindersGORM supports the concept of dynamic finders. A dynamic finder looks like a static method invocation, but the methods themselves don't actually exist in any form at the code level.Instead, a method is auto-magically generated using code synthesis at runtime, based on the properties of a given class. Take for example the
Book class:
class Book { String title Date releaseDate Author author } class Author { String name }
Book class has properties such as
releaseDate and
author. These can be used by the findBy and findAllBy methods in the form of "method expressions":
def book = Book.findByTitle("The Stand")book = Book.findByTitleLike("Harry Pot%")book = Book.findByReleaseDateBetween( firstDate, secondDate )book = Book.findByReleaseDateGreaterThan( someDate )book = Book.findByTitleLikeOrReleaseDateLessThan( "%Something%", someDate )
Method ExpressionsA method expression in GORM is made up of the prefix such as findBy followed by an expression that combines one or more properties. The basic form is:
The tokens marked with a '?' are optional. Each comparator changes the nature of the query. For example:
Book.findBy([Property][Comparator][Boolean Operator])?[Property][Comparator]
In the above example the first query is equivalent to equality whilst the latter, due to the
def book = Book.findByTitle("The Stand")book = Book.findByTitleLike("Harry Pot%")
Like comparator, is equivalent to a SQL
like expression.The possible comparators include:
InList- In the list of given values
LessThan- less than the given value
LessThanEquals- less than or equal a give value
GreaterThan- greater than a given value
GreaterThanEquals- greater than or equal a given value
Like- Equivalent to a SQL like expression
Ilike- Similar to a
Like, except case insensitive
NotEqual- Negates equality
Between- Between two values (requires two arguments)
IsNotNull- Not a null value (doesn't require an argument)
IsNull- Is a null value (doesn't require an argument)
def now = new Date()
def lastWeek = now - 7
def book = Book.findByReleaseDateBetween( lastWeek, now )books = Book.findAllByReleaseDateIsNull()
books = Book.findAllByReleaseDateIsNotNull()
Boolean logic (AND/OR)Method expressions can also use a boolean operator to combine two criteria:
In this case we're using
def books = Book.findAllByTitleLikeAndReleaseDateGreaterThan("%Java%", new Date()-30)
And in the middle of the query to make sure both conditions are satisfied, but you could equally use
At the moment, you can only use dynamic finders with a maximum of two criteria, i.e. the method name can only have one boolean operator. If you need to use more, you should consider using either Criteria or the HQL.
def books = Book.findAllByTitleLikeOrReleaseDateGreaterThan("%Java%", new Date()-30)
Querying AssociationsAssociations can also be used within queries:
In this case if the
def author = Author.findByName("Stephen King")def books = author ? Book.findAllByAuthor(author) : []
Author instance is not null we use it in a query to obtain all the
Book instances for the given
Pagination & SortingThe same pagination and sorting parameters available on the list method can also be used with dynamic finders by supplying a map as the final parameter:
def books = Book.findAllByTitleLike("Harry Pot%", [max:3, offset:2, sort:"title", order:"desc"])
5.4.2 CriteriaCriteria is a type safe, advanced way to query that uses a Groovy builder to construct potentially complex queries. It is a much better alternative to using StringBuffer.Criteria can be used either via the createCriteria or withCriteria methods. The builder uses Hibernate's Criteria API, the nodes on this builder map the static methods found in the Restrictions class of the Hibernate Criteria API. Example Usage:
This criteria will select up to 10
def c = Account.createCriteria() def results = c { between("balance", 500, 1000) eq("branch", "London") or { like("holderFirstName", "Fred%") like("holderFirstName", "Barney%") } maxResults(10) order("holderLastName", "desc") }
Account objects matching the following criteria:
balanceis between 500 and 1000
branchis 'London'
holderFirstNamestarts with 'Fred' or 'Barney'
Conjunctions and DisjunctionsAs demonstrated in the previous example you can group criteria in a logical OR using a
or { } block:
This also works with logical AND:
or { between("balance", 500, 1000) eq("branch", "London") }
And you can also negate using logical NOT:
and { between("balance", 500, 1000) eq("branch", "London") }
All top level conditions are implied to be AND'd together.
not { between("balance", 500, 1000) eq("branch", "London") }
Querying AssociationsAssociations can be queried by having a node that matches the property name. For example say the
Account class had many
Transaction objects:
We can query this association by using the property name
class Account {
static hasMany = [transactions:Transaction]
transaction as a builder node:
The above code will find all the
def c = Account.createCriteria()
def now = new Date()
def results = c.list {
transactions {
between('date',now-10, now)
Account instances that have performed
transactions within the last 10 days.
You can also nest such association queries within logical blocks:
Here we find all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days.
def c = Account.createCriteria()
def now = new Date()
def results = c.list {
or {
transactions {
between('date',now-10, now)
Querying with ProjectionsProjections may be used to customise the results. To use projections you need to define a "projections" node within the criteria builder tree. There are equivalent methods within the projections node to the methods found in the Hibernate Projections class:
def c = Account.createCriteria()def numberOfBranches = c.get { projections { countDistinct('branch') } }
Using SQL RestrictionsYou can access Hibernate's SQL Restrictions capabilities.
def c = Person.createCriteria()def peopleWithShortFirstNames = c.list {
sqlRestriction "char_length( first_name ) <= 4"
Note that the parameter there is SQL. The
first_nameattribute referenced in the example relates to the persistence model, not the object model. The
Personclass may have a property named
firstNamewhich is mapped to a column in the database named
first_name.Also note that the SQL used here is not necessarily portable across databases.
Using Scrollable ResultsYou can use Hibernate's ScrollableResults feature by calling the scroll method:
To quote the documentation of Hibernate ScrollableResults:
def results = crit.scroll {
def f = results.first()
def l = results.last()
def n = results.next()
def p = results.previous()def future = results.scroll(10)
def accountNumber = results.getLong('number')
A result iterator that allows moving around within the results by arbitrary increments. The Query / ScrollableResults pattern is very similar to the JDBC PreparedStatement/ ResultSet pattern and the semantics of methods of this interface are similar to the similarly named methods on ResultSet.Contrary to JDBC, columns of results are numbered from zero.
Setting properties in the Criteria instanceIf a node within the builder tree doesn't match a particular criterion it will attempt to set a property on the Criteria object itself. Thus allowing full access to all the properties in this class. The below example calls
setMaxResults and
setFirstResult on the Criteria instance:
import org.hibernate.FetchMode as FM … def results = c.list { maxResults(10) firstResult(50) fetchMode("aRelationship", FM.JOIN) }
Querying with Eager FetchingIn the section on Eager and Lazy Fetching we discussed how to declaratively specify fetching to avoid the N+1 SELECT problem. However, this can also be achieved using a criteria query:
Notice the usage of the
def criteria = Task.createCriteria()
def tasks = criteria.list{
eq "assignee.id", task.assignee.id
join 'assignee'
join 'project'
order 'priority', 'asc'
join method: it tells the criteria API to use a
JOIN to fetch the named associations with the
Task instances. It's probably best not to use this for one-to-many associations though, because you will most likely end up with duplicate results. Instead, use the 'select' fetch mode:
Although this approach triggers a second query to get the
import org.hibernate.FetchMode as FM … def results = Airport.withCriteria { eq "region", "EMEA" fetchMode "flights", FM.SELECT }
flights association, you will get reliable results - even with the
maxResults option.
An important point to bear in mind is that if you include associations in the query constraints, those associations will automatically be eagerly loaded. For example, in this query:
joinare general settings of the query and can only be specified at the top-level, i.e. you cannot use them inside projections or association constraints.
def results = Airport.withCriteria { eq "region", "EMEA" flights { like "number", "BA%" } }
flights collection would be loaded eagerly via a join even though the fetch mode has not been explicitly set.
Method ReferenceIf you invoke the builder with no method name such as:
The build defaults to listing all the results and hence the above is equivalent to:
c { … }
c.list { … }
|This is the default method. It returns all matching rows.
|Returns a unique result set, i.e. just one row. The criteria has to be formed that way, that it only queries one row. This method is not to be confused with a limit to just the first row.
|Returns a scrollable result set.
|If subqueries or associations are used, one may end up with the same row multiple times in the result set, this allows listing only distinct entities and is equivalent to
DISTINCT_ROOT_ENTITY of the CriteriaSpecification class.
|Returns the number of matching rows.
5.4.3 Hibernate Query Language (HQL)GORM classes also support Hibernate's query language HQL, a very complete reference for which can be found Chapter 14. HQL: The Hibernate Query Language of the Hibernate documentation.GORM provides a number of methods that work with HQL including find, findAll and executeQuery. An example of a query can be seen below:
def results =
Book.findAll("from Book as b where b.title like 'Lord of the%'")
Positional and Named ParametersIn this case the value passed to the query is hard coded, however you can equally use positional parameters:
def results = Book.findAll("from Book as b where b.title like ?", ["The Shi%"])
Or even named parameters:
def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = ?", [author])
def results = Book.findAll("from Book as b where b.title like :search or b.author like :search", [search:"The Shi%"])
def author = Author.findByName("Stephen King") def books = Book.findAll("from Book as book where book.author = :author", [author: author])
Multiline QueriesIf you need to separate the query across multiple lines you can use a line continuation character:
def results = Book.findAll("\
from Book as b, \
Author as a \
where b.author = a and a.surname = ?", ['Smith'])
Groovy multiline strings will NOT work with HQL queries
Pagination and SortingYou can also perform pagination and sorting whilst using HQL queries. To do so simply specify the pagination options as a map at the end of the method call and include an "ORDER BY" clause in the HQL:
def results =
Book.findAll("from Book as b where b.title like 'Lord of the%' order by b.title asc",
[max:10, offset:20])
5.5 Advanced GORM FeaturesThe following sections cover more advanced usages of GORM including caching, custom mapping and events.
5.5.1 Events and Auto TimestampingGORM supports the registration of events as methods that get fired when certain events occurs such as deletes, inserts and updates. The following is a list of supported events:
beforeInsert- Executed before an object is initially persisted to the database
beforeUpdate- Executed before an object is updated
beforeDelete- Executed before an object is deleted
beforeValidate- Executed before an object is validated
afterInsert- Executed after an object is persisted to the database
afterUpdate- Executed after an object has been updated
afterDelete- Executed after an object has been deleted
onLoad- Executed when an object is loaded from the database
Do not attempt to flush the session within an event (such as with obj.save(flush:true)). Since events are fired during flushing this will cause a StackOverflowError.
Event types
The beforeInsert eventFired before an object is saved to the db
class Person {
Date dateCreated def beforeInsert() {
dateCreated = new Date()
The beforeUpdate eventFired before an existing object is updated
class Person { Date dateCreated Date lastUpdated def beforeInsert() { dateCreated = new Date() } def beforeUpdate() { lastUpdated = new Date() } }
The beforeDelete eventFired before an object is deleted.
Notice the usage of
class Person { String name Date dateCreated Date lastUpdated def beforeDelete() { ActivityTrace.withNewSession { new ActivityTrace(eventName:"Person Deleted",data:name).save() } } }
withNewSession method above. Since events are triggered whilst Hibernate is flushing using persistence methods like
save() and
delete() won't result in objects being saved unless you run your operations with a new
Session.Fortunately the
withNewSession method allows you to share the same transactional JDBC connection even though you're using a different underlying
The beforeValidate eventFired before an object is validated.
class Person { String name static constraints = { name size: 5..45 } def beforeValidate() { name = name?.trim() } }
beforeValidate method is run before any validators are run.GORM supports an overloaded version of
beforeValidate which accepts a
List parameter which may include
the names of the properties which are about to be validated. This version of
beforeValidate will be called
when the
validate method has been invoked and passed a
List of property names as an argument.
class Person { String name String town Integer age static constraints = { name size: 5..45 age range: 4..99 } def beforeValidate(List propertiesBeingValidated) { // do pre validation work based on propertiesBeingValidated } }def p = new Person(name: 'Jacob Brown', age: 10) p.validate(['age', 'name'])
Note that whenEither or both versions of
validateis triggered indirectly because of a call to the
savemethod that the
validatemethod is being invoked with no arguments, not a
Listthat includes all of the property names.
beforeValidate may be defined in a domain class. GORM will
prefer the
List version if a
List is passed to
validate but will fall back on the
no-arg version if the
List version does not exist. Likewise, GORM will prefer the
no-arg version if no arguments are passed to
validate but will fall back on the
List version if the no-arg version does not exist. In that case, null
is passed to
The onLoad/beforeLoad eventFired immediately before an object is loaded from the db:
class Person { String name Date dateCreated Date lastUpdated def onLoad() { log.debug "Loading ${id}" } }
beforeLoad() is effectively a synonym for
onLoad(), so only declare one or the other.
The afterLoad eventFired immediately after an object is loaded from the db:
class Person { String name Date dateCreated Date lastUpdated def afterLoad() { name = "I'm loaded" } }
Custom Event ListenersYou can also register event handler classes in an application's
grails-app/conf/spring/resources.groovy or in the
doWithSpring closure in a plugin descriptor by registering a Spring bean named
hibernateEventListeners. This bean has one property,
listenerMap which specifies the listeners to register for various Hibernate events.The values of the map are instances of classes that implement one or more Hibernate listener interfaces. You can use one class that implements all of the required interfaces, or one concrete class per interface, or any combination. The valid map keys and corresponding interfaces are listed here:
AuditEventListener which implements
PostUpdateEventListener, and
PostDeleteEventListener using the following in an application:
or use this in a plugin:
beans = { auditListener(AuditEventListener) hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert':auditListener, 'post-update':auditListener, 'post-delete':auditListener] } }
def doWithSpring = { auditListener(AuditEventListener) hibernateEventListeners(HibernateEventListeners) { listenerMap = ['post-insert':auditListener, 'post-update':auditListener, 'post-delete':auditListener] } }
Automatic timestampingThe examples above demonstrated using events to update a
lastUpdated and
dateCreated property to keep track of updates to objects. However, this is actually not necessary. By merely defining a
lastUpdated and
dateCreated property these will be automatically updated for you by GORM.If this is not the behaviour you want you can disable this feature with:
class Person { Date dateCreated Date lastUpdated static mapping = { autoTimestamp false } }
If you put
nullable: falseconstraints on either
lastUpdated, your domain instances will fail validation - probably not what you want. Leave constraints off these properties unless you have disabled automatic timestamping.
5.5.2 Custom ORM MappingGrails domain classes can be mapped onto many legacy schemas via an Object Relational Mapping Domain Specify Language. The following sections takes you through what is possible with the ORM DSL.
None if this is necessary if you are happy to stick to the conventions defined by GORM for table, column names and so on. You only needs this functionality if you need to in anyway tailor the way GORM maps onto legacy schemas or performs cachingCustom mappings are defined using a a static
mapping block defined within your domain class:
class Person {
static mapping = { }
220.127.116.11 Table and Column Names
Table namesThe database table name which the class maps to can be customized using a call to
In this case the class would be mapped to a table called
class Person {
static mapping = {
table 'people'
people instead of the default name of
Column namesIt is also possible to customize the mapping for individual columns onto the database. For example if its the name you want to change you can do:
In this case we define method calls that match each property name (in this case
class Person { String firstName static mapping = { table 'people' firstName column:'First_Name' } }
firstName). We then use the named parameter
column, to specify the column name to map onto.
Column typeGORM supports configuration of Hibernate types via the DSL using the type attribute. This includes specifing user types that subclass the Hibernate org.hibernate.usertype.UserType class, which allows complete customization of how a type is persisted. As an example if you had a
PostCodeType you could use it as follows:
Alternatively if you just wanted to map it to one of Hibernate's basic types other than the default chosen by Grails you could use:
class Address { String number String postCode static mapping = { postCode type:PostCodeType } }
This would make the
class Address { String number String postCode static mapping = { postCode type:'text' } }
postCode column map to the SQL TEXT or CLOB type depending on which database is being used.See the Hibernate documentation regarding Basic Types for further information.
Many-to-One/One-to-One MappingsIn the case of associations it is also possible to change the foreign keys used to map associations. In the case of a many- or one-to-one association this is exactly the same as any regular column. For example consider the following:
By default the
class Person { String firstName Address address static mapping = { table 'people' firstName column:'First_Name' address column:'Person_Address_Id' } }
address association would map to a foreign key column called
address_id. By using the above mapping we have changed the name of the foreign key column to
One-to-Many MappingWith a bidirectional one-to-many you can change the foreign key column used simple by changing the column name on the many side of the association as per the example in the previous section on one-to-one associations. However, with unidirectional association the foreign key needs to be specified on the association itself. For example given a unidirectional one-to-many relationship between
Person and
Address the following code will change the foreign key in the
address table:
If you don't want the column to be in the
class Person { String firstName static hasMany = [addresses:Address] static mapping = { table 'people' firstName column:'First_Name' addresses column:'Person_Address_Id' } }
address table, but instead some intermediate join table you can use the
joinTable parameter:
class Person { String firstName static hasMany = [addresses:Address] static mapping = { table 'people' firstName column:'First_Name' addresses joinTable:[name:'Person_Addresses', key:'Person_Id', column:'Address_Id'] } }
Many-to-Many MappingGrails, by default maps a many-to-many association using a join table. For example consider the below many-to-many association:
In this case Grails will create a join table called
class Group { … static hasMany = [people:Person] } class Person { … static belongsTo = Group static hasMany = [groups:Group] }
group_person containing foreign keys called
person_id and
group_id referencing the
person and
group tables. If you need to change the column names you can specify a column within the mappings for each class.
You can also specify the name of the join table to use:
class Group { … static mapping = { people column:'Group_Person_Id' } } class Person { … static mapping = { groups column:'Group_Group_Id' } }
class Group { … static mapping = { people column:'Group_Person_Id',joinTable:'PERSON_GROUP_ASSOCIATIONS' } } class Person { … static mapping = { groups column:'Group_Group_Id',joinTable:'PERSON_GROUP_ASSOCIATIONS' } }
220.127.116.11 Caching Strategy
Setting up cachingHibernate features a second-level cache with a customizable cache provider. This needs to be configured in the
grails-app/conf/DataSource.groovy file as follows:
You can of course customize these settings how you desire, for example if you want to use a distributed caching mechanism.
hibernate { cache.use_second_level_cache=true cache.use_query_cache=true cache.provider_class='org.hibernate.cache.EhCacheProvider' }
For further reading on caching and in particular Hibernate's second-level cache, refer to the Hibernate documentation on the subject.
Caching instancesIn your mapping block to enable caching with the default settings use a call to the
cache method:
This will configure a 'read-write' cache that includes both lazy and non-lazy properties. If you need to customize this further you can do:
class Person { .. static mapping = { table 'people' cache true } }
class Person {
static mapping = {
table 'people'
cache usage:'read-only', include:'non-lazy'
Caching associationsAs well as the ability to use Hibernate's second level cache to cache instances you can also cache collections (associations) of objects. For example:
This will enable a 'read-write' caching mechanism on the addresses collection. You can also use:
class Person { String firstName static hasMany = [addresses:Address] static mapping = { table 'people' version false addresses column:'Address', cache:true } } class Address { String number String postCode }
To further configure the cache usage.
cache:'read-write' // or 'read-only' or 'transactional'
Caching QueriesYou can cache queries such as dynamic finders and criteria. To do so using a dynamic finder you can pass the
cache argument:
def person = Person.findByFirstName("Fred", [cache:true])
Note that in order for the results of the query to be cached, you still need to enable caching in your mapping as discussed in the previous section.You can also cache criteria queries:
def people = Person.withCriteria {
like('firstName', 'Fr%')
cache true
Cache usagesBelow is a description of the different cache settings and their usages:
read-only- If your application needs to read but never modify instances of a persistent class, a read-only cache may be used.
read-write- If the application needs to update data, a read-write cache might be appropriate.
nonstrict-read-write- If the application only occasionally needs to update data (ie. if it is extremely unlikely that two transactions would try to update the same item simultaneously) and strict transaction isolation is not required, a
nonstrict-read-writecache might be appropriate.
transactional- The
transactionalcache strategy provides support for fully transactional cache providers such as JBoss TreeCache. Such a cache may only be used in a JTA environment and you must specify
hibernate.transaction.manager_lookup_classin the
18.104.22.168 Inheritance StrategiesBy default GORM classes uses
table-per-hierarchy inheritance mapping. This has the disadvantage that columns cannot have a
NOT-NULL constraint applied to them at the db level. If you would prefer to use a
table-per-subclass inheritance strategy you can do so as follows:
The mapping of the root
class Payment { Long id Long version Integer amount static mapping = { tablePerHierarchy false } } class CreditCardPayment extends Payment { String cardNumber }
Payment class specifies that it will not be using
table-per-hierarchy mapping for all child classes.
22.214.171.124 Custom Database IdentityYou can customize how GORM generates identifiers for the database using the DSL. By default GORM relies on the native database mechanism for generating ids. This is by far the best approach, but there are still many schemas that have different approaches to identity.To deal with this Hibernate defines the concept of an id generator. You can customize the id generator and the column it maps to as follows:
In this case we're using one of Hibernate's built in 'hilo' generators that uses a separate table to generate ids.
class Person { .. static mapping = { table 'people' version false id generator:'hilo', params:[table:'hi_value',column:'next_value',max_lo:100] } }
For more information on the different Hibernate generators refer to the Hibernate reference documentationNote that if you want to merely customise the column that the id lives on you can do:
class Person { .. static mapping = { table 'people' version false id column:'person_id' } }
18.104.22.168 Composite Primary KeysGORM supports the concept of composite identifiers (identifiers composed from 2 or more properties). It is not an approach we recommend, but is available to you if you need it:
The above will create a composite id of the
class Person { String firstName String lastName static mapping = { id composite:['firstName', 'lastName'] } }
firstName and
lastName properties of the Person class. When you later need to retrieve an instance by id you have to use a prototype of the object itself:
def p = Person.get(new Person(firstName:"Fred", lastName:"Flintstone")) println p.firstName
22.214.171.124 Database IndicesTo get the best performance out of your queries it is often necessary to tailor the table index definitions. How you tailor them is domain specific and a matter of monitoring usage patterns of your queries. With GORM's DSL you can specify which columns need to live in which indexes:
Note that you cannot have any spaces in the value of the
class Person { String firstName String address static mapping = { table 'people' version false id column:'person_id' firstName column:'First_Name', index:'Name_Idx' address column:'Address', index:'Name_Idx,Address_Index' } }
index attribute; in this example
index:'Name_Idx, Address_Index' will cause an error.
22.214.171.124 Optimistic Locking and VersioningAs discussed in the section on Optimistic and Pessimistic Locking, by default GORM uses optimistic locking and automatically injects a
version property into every class which is in turn mapped to a
version column at the database level.If you're mapping to a legacy schema this can be problematic, so you can disable this feature by doing the following:
class Person { .. static mapping = { table 'people' version false } }
If you disable optimistic locking you are essentially on your own with regards to concurrent updates and are open to the risk of users losing (due to data overriding) data unless you use pessimistic locking
22.214.171.124 Eager and Lazy Fetching
Lazy CollectionsAs discussed in the section on Eager and Lazy fetching, GORM collections are lazily loaded by default but you can change this behaviour via the ORM DSL. There are several options available to you, but the most common ones are:
- lazy: false
- fetch: 'join'
The first option,
class Person { String firstName Pet pet static hasMany = [addresses:Address] static mapping = { addresses lazy:false pet fetch: 'join' } }class Address { String street String postCode }class Pet { String name }
lazy: false , ensures that when a
Person instance is loaded, its
addresses collection is loaded at the same time with a second SELECT. The second option is basically the same, except the collection is loaded via a JOIN rather than another SELECT. Typically you will want to reduce the number of queries, so
fetch: 'join' will be the more appropriate option. On the other hand, it could feasibly be the more expensive approach if your domain model and data result in more and larger results than would otherwise be necessary.For more advanced users, the other settings available are:
- batchSize: N
- lazy: false, batchSize: N
If a query returns multiple
class Person { String firstName Pet pet static mapping = { pet batchSize: 5 } }
Person instances, then when we access the first
pet property, Hibernate will fetch that
Pet plus the four next ones. You can get the same behaviour with eager loading by combining
batchSize with the
lazy: false option. You can find out more about these options in the Hibernate user guide and this primer on fetching strategies. Note that ORM DSL does not currently support the "subselect" fetching strategy.
Lazy Single-Ended AssociationsIn GORM, one-to-one and many-to-one associations are by default lazy. Non-lazy single ended associations can be problematic when you load many entities because each non-lazy association will result in an extra SELECT statement. If the associated entities also have non-lazy associations, the number of queries grows exponentially!If you want to make a one-to-one or many-to-one association non-lazy/eager, you can use the same technique as for lazy collections:
Here we configure GORM to load the associated
class Person { String firstName }class Address { String street String postCode static belongsTo = [person:Person] static mapping = { person lazy:false } }
Person instance (through the
person property) whenever an
Address is loaded.
Lazy Single-Ended Associations and ProxiesIn order to facilitate single-ended lazy associations Hibernate uses runtime generated proxies. The way this works is that Hibernate dynamically subclasses the proxied entity to create the proxy.Consider the previous example but with a lazily-loaded
person association: Hibernate will set the
person property to a proxy that is a subclass of
Person. When you call any of the getters or setters on that proxy, Hibernate will load the entity from the database.Unfortunately this technique can produce surprising results. Consider the following example classes:
and assume that we have a single
class Pet { String name } class Dog extends Pet { } class Person { String name Pet pet }
Person instance with a
Dog as his or her
pet. The following code will work as you would expect:
But this won't:
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.get(person.petId) instanceof Dog
For some reason, the second assertion fails. To add to the confusion, this will work:
def person = Person.get(1) assert person.pet instanceof Dog assert Pet.list()[0] instanceof Dog
What's going on here? It's down to a combination of how proxies work and the guarantees that the Hibernate session makes. When you load the
assert Pet.list()[0] instanceof Dog
Person instance, Hibernate creates a proxy for its
pet relation and attaches it to the session. Once that happens, whenever you retrieve that
Pet instance via a query, a
get(), or the
pet relation within the same session , Hibernate gives you the proxy.Fortunately for us, GORM automatically unwraps the proxy when you use
get() and
findBy*(), or when you directly access the relation. That means you don't have to worry at all about proxies in the majority of cases. But GORM doesn't do that for objects returned via a query that returns a list, such as
list() and
findAllBy*(). However, if Hibernate hasn't attached the proxy to the session, those queries will return the real instances - hence why the last example works.You can protect yourself to a degree from this problem by using the
instanceOf method by GORM:
However, it won't help here casting is involved. For example, the following code will throw a
def person = Person.get(1) assert Pet.list()[0].instanceOf(Dog)
ClassCastException because the first pet in the list is a proxy instance with a class that is neither
Dog nor a sub-class of
Of course, it's best not to use static types in this situation. If you use an untyped variable for the pet instead, you can access any
def person = Person.get(1) Dog pet = Pet.list()[0]
Dog properties or methods on the instance without any problems.These days it's rare that you will come across this issue, but it's best to be aware of it just in case. At least you will know why such an error occurs and be able to work around it.
22.214.171.124 Custom Cascade BehaviourAs describes in the section on cascading updates, the primary mechanism to control the way updates and deletes are cascading from one association to another is the belongsTo static property.However, the ORM DSL gives you complete access to Hibernate's transitive persistence capabilities via the
cascade attribute.Valid settings for the cascade attribute include:
- merge - merges the state of a detached association
- save-update - cascades only saves and updates to an association
- delete - cascades only deletes to an association
- lock - useful if a pessimistic lock should be cascaded to its associations
- refresh - cascades refreshes to an association
- evict - cascades evictions (equivalent to discard() in GORM) to associations if set
- all - cascade ALL operations to associations
- all-delete-orphan - Applies only to one-to-many associations and indicates that when a child is removed from an association then it should be automatically deleted. Children are also deleted when the parent is.
It is advisable to read the section in the Hibernate documentation on transitive persistence to obtain a better understanding of the different cascade styles and recommendation for their usageTo specific the cascade attribute simply define one or many (comma-separated) of the aforementioned settings as its value:
class Person { String firstName static hasMany = [addresses:Address] static mapping = { addresses cascade:"all-delete-orphan" } } class Address { String street String postCode }
18.104.22.168 Custom Hibernate TypesYou saw in an earlier section that you can use composition (via the
embedded property) to break a table into multiple objects. You can achieve a similar effect via Hibernate's custom user types. These are not domain classes themselves, but plain Java or Groovy classes with associated. Each of these types also has a corresponding "meta-type" class that implements org.hibernate.usertype.UserType.The Hibernate reference manual has some information on custom types, but here we will focus on how to map them in Grails. Let's start by taking a look at a simple domain class that uses an old-fashioned (pre-Java 1.5) type-safe enum class:
All we have done is declare the
class Book { String title String author Rating rating static mapping = { rating type: RatingUserType } }
rating field the enum type and set the property's type in the custom mapping to the corresponding
UserType implementation. That's all you have to do to start using your custom type. If you want, you can also use the other column settings such as "column" to change the column name and "index" to add it to an index.Custom types aren't limited to just a single column - they can be mapped to as many columns as you want. In such cases you need to explicitly define in the mapping what columns to use, since Hibernate can only use the property name for a single column. Fortunately, Grails allows you to map multiple columns to a property using this syntax:
The above example will create "first_name" and "last_name" columns for the
class Book { String title Name author Rating rating static mapping = { name type: NameUserType, { column name: "first_name" column name: "last_name" } rating type: RatingUserType } }
author property. You'll be pleased to know that you can also use some of the normal column/property mapping attributes in the column definitions. For example:
The column definitions do not support the following attributes:
column name: "first_name", index: "my_idx", unique: true
cache, and
joinTable.One thing to bear in mind with custom types is that they define the SQL types for the corresponding database columns. That helps take the burden of configuring them yourself, but what happens if you have a legacy database that uses a different SQL type for one of the columns? In that case, you need to override column's SQL type using the
sqlType attribute:
Mind you, the SQL type you specify needs to still work with the custom type. So overriding a default of "varchar" with "text" is fine, but overriding "text" with "yes_no" isn't going to work.
class Book { String title Name author Rating rating static mapping = { name type: NameUserType, { column name: "first_name", sqlType: "text" column name: "last_name", sqlType: "text" } rating type: RatingUserType, sqlType: "text" } }
184.108.40.206 Derived PropertiesA derived property is a property that takes its value from a SQL expression, often but not necessarily based on the value of some other persistent property. Consider a Product class like this:
If the
class Product { Float price Float taxRate Float tax }
tax property is derived based on the value of
price and
properties then there may be no need to persist the
tax property in the
database. The SQL used to derive the value of a derived property may be
expressed in the ORM DSL like this:
Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the persistence model not the object model, which is why the example refers to
class Product { Float price Float taxRate Float tax static mapping = { tax formula: 'PRICE * TAX_RATE' } }
PRICE and
TAX_RATE instead of
price and
taxRate.With that in place, when a Product is retrieved with something like
Product.get(42), the SQL that is generated to support
that will look something like this:
Since the
select product0_.id as id1_0_, product0_.version as version1_0_, product0_.price as price1_0_, product0_.tax_rate as tax4_1_0_, product0_.PRICE * product0_.TAX_RATE as formula1_0_ from product product0_ where product0_.id=?
tax property is being derived at runtime and not stored in the
database it might seem that the same effect could be achieved by adding
a method like
getTax() to the
Product class that simply returns the
product of the
taxRate and
price properties. With an approach like
that you would give up the ability query the database based on the value
of the
tax property. Using a derived property allows exactly that. To
retrieve all
Product objects that have a
tax value greater than 21.12
you could execute a query like this:
Derived properties may be referenced in the Criteria API:
The SQL that is generated to support either of those would look something like this:
Product.withCriteria { gt 'tax', 21.12f }
select this_.id as id1_0_, this_.version as version1_0_, this_.price as price1_0_, this_.tax_rate as tax4_1_0_, this_.PRICE * this_.TAX_RATE as formula1_0_ from product this_ where this_.PRICE * this_.TAX_RATE>?
Note that because the value of a derived property is generated in the database and depends on the execution of SQL code, derived properties may not have GORM constraints applied to them. If constraints are specified for a derived property, they will be ignored.
188.8.131.52 Custom Naming StrategyBy default Grails uses Hibernate's
ImprovedNamingStrategy to convert domain class Class and field names to SQL table and column names by converting from camel-cased Strings to ones that use underscores as word separators. You can customize these on a per-instance basis in the
mapping closure but if there's a consistent pattern you can specify a different
NamingStrategy class to use.Configure the class name to be used in
grails-app/conf/DataSource.groovy in the
hibernate section, e.g.
You can use an existing class or write your own, for example one that prefixes table names and column names:
dataSource { pooled = true dbCreate = "create-drop" … }hibernate { cache.use_second_level_cache = true … naming_strategy = com.myco.myproj.CustomNamingStrategy }
package com.myco.myprojimport org.hibernate.cfg.ImprovedNamingStrategy import org.hibernate.util.StringHelperclass CustomNamingStrategy extends ImprovedNamingStrategy { String classToTableName(String className) { "table_" + StringHelper.unqualify(className) } String propertyToColumnName(String propertyName) { "col_" + StringHelper.unqualify(propertyName) } }
5.5.3 Default Sort OrderYou can sort objects using queries arguments such as those found in the list method:
However, you can also declare the default sort order for a collection in the mapping:
def airports = Airport.list(sort:'name')
The above means that all collections of
class Airport { … static mapping = { sort "name" } }
Airports will be sorted by default by the airport name. If you also want to change the sort order , use this syntax:
Finally, you can configure the sorting at the association level:
class Airport { … static mapping = { sort name:"desc" } }
In this case, the
class Airport { … static hasMany = [flights:Flight] static mapping = { flights sort:'number', order:'desc' } }
flights collection will always be sorted in descending order of flight number.
These mappings will not work for default unidirectional one-to-many or many-to-many relationships because they involve a join table. See this issue for more details. Consider using a
SortedSet or queries with sort parameters to fetch the data you need.
5.6 Programmatic TransactionsGrails is built on Spring and hence uses Spring's Transaction abstraction for dealing with programmatic transactions. However, GORM classes have been enhanced to make this more trivial through the withTransaction method which accepts a block the first argument to which is the Spring TransactionStatus object.A typical usage scenario is as follows:
In this example we rollback the transactions if the destination account is not active and if any exception are thrown during the process the transaction will automatically be rolled back.You can also use "save points" to rollback a transaction to a particular point in time if you don't want to rollback the entire transaction. This can be achieved through the use of Spring's SavePointManager interface.The withTransaction method deals with the begin/commit/rollback logic for you within the scope of the block.
def transferFunds = { Account.withTransaction { status -> def source = Account.get(params.from) def dest = Account.get(params.to) def amount = params.amount.toInteger() if(source.active) { source.balance -= amount if(dest.active) { dest.amount += amount } else { status.setRollbackOnly() } } }}
5.7 GORM and ConstraintsAlthough constraints are covered in the Validation section, it is important to mention them here as some of the constraints can affect the way in which the database schema is generated.Where feasible, Grails uses a domain class's constraints to influence the database columns generated for the corresponding domain class properties.Consider the following example. Suppose we have a domain model with the following property.
By default, in MySQL, Grails would define these columns as...
String name String description
But perhaps the business rules for this domain class state that a description can be up to 1000 characters in length. If that were the case, we'd likely define the column as follows if we were creating the table via an SQL script.
column name | data type description | varchar(255)
Chances are we'd also want to have some application-based validation to make sure we don't exceed that 1000 character limit before we persist any records. In Grails, we achieve this validation via constraints. We'd add the following constraint declaration to the domain class.
column name | data type description | TEXT
This constraint would provide both the application-based validation we want and it would also cause the schema to be generated as shown above. Below is a description of the other constraints that influence schema generation.
static constraints = {
Constraints Affecting String Properties
maxSize or the
size constraint is defined, Grails sets the maximum column length based on the constraint value.In general, it's not advisable to use both constraints on the same domain class property. However, if both the
maxSize constraint and the
size constraint are defined, then Grails sets the column length to the minimum of the
maxSize constraint and the upper bound of the size constraint. (Grails uses the minimum of the two, because any length that exceeds that minimum will result in a validation error.)If the inList constraint is defined (and the
maxSize and the
size constraints are not defined), then Grails sets the maximum column length based on the length of the longest string in the list of valid values. For example, given a list including values "Java", "Groovy", and "C++", Grails would set the column length to 6 (i.e., the number of characters in the string "Groovy").
Constraints Affecting Numeric Properties
max constraint, the
min constraint, or the
range constraint is defined, Grails attempts to set the column precision based on the constraint value. (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)In general, it's not advisable to combine the pair min/max and range constraints together on the same domain class property. However, if both of these constraints is defined, then Grails uses the minimum precision value from the constraints. (Grails uses the minimum of the two, because any length that exceeds that minimum precision will result in a validation error.)
scale based on the constraint value. This rule only applies to floating point numbers (i.e., java.lang.Float, java.Lang.Double, java.lang.BigDecimal, or subclasses of java.lang.BigDecimal). (The success of this attempted influence is largely dependent on how Hibernate interacts with the underlying DBMS.)The constraints define the minimum/maximum numeric values, and Grails derives the maximum number of digits for use in the precision. Keep in mind that specifying only one of min/max constraints will not affect schema generation (since there could be large negative value of property with max:100, for example), unless specified constraint value requires more digits than default Hibernate column precision is (19 at the moment). For example...
would yield:
someFloatValue(max:1000000, scale:3)
someFloatValue DECIMAL(19, 3) // precision is default
would yield:
someFloatValue(max:12345678901234567890, scale:5)
someFloatValue DECIMAL(25, 5) // precision = digits in max + scale
would yield:
someFloatValue(max:100, min:-100000)
someFloatValue DECIMAL(8, 2) // precision = digits in min + default scale
6. The Web Layer
6.1 ControllersA controller handles requests and creates or prepares the response and is request-scoped. In other words a new instance is created for each request. A controller can generate the response or delegate to a view. To create a controller simply create a class whose name ends with
Controller and place it within the
grails-app/controllers directory.The default URL Mapping setup ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URI within the controller name URI.
6.1.1 Understanding Controllers and Actions
Creating a controllerControllers can be created with the create-controller target. For example try running the following command from the root of a Grails project:
The command will result in the creation of a controller at the location
grails create-controller book
class BookController { … }
BookController by default maps to the /book URI (relative to your application root).
create-controller command is merely for convenience and you can just as easily create controllers using your favorite text editor or IDE
Creating ActionsA controller can have multiple properties that are each assigned a block of code. Each of these properties maps to a URI:
This example maps to the
class BookController { def list = { // do controller logic // create model return model } }
/book/list URI by default thanks to the property being named
The Default ActionA controller has the concept of a default URI that maps to the root URI of the controller. By default the default URI in this case is
/book. The default URI is dictated by the following rules:
- If only one action is present the default URI for a controller maps to that action.
- If you define an
indexaction which is the action that handles requests when no action is specified in the URI
- Alternatively you can set it explicitly with the
static defaultAction = "list"
6.1.2 Controllers and Scopes
Available ScopesScopes are essentially hash like objects that allow you to store variables. The following scopes are available to controllers:
- servletContext - Also known as application scope, this scope allows you to share state across the entire web application. The servletContext is an instance of javax.servlet.ServletContext
- session - The session allows associating state with a given user and typically uses cookies to associate a session with a client. The session object is an instance of HttpSession
- request - The request object allows the storage of objects for the current request only. The request object is an instance of HttpServletRequest
- params - Mutable map of incoming request (CGI) parameters
- flash - See below.
Accessing ScopesScopes can be accessed using the variable names above in combination with Groovy's array index operator even on classes provided by the Servlet API such as the HttpServletRequest:
You can even access values within scopes using the de-reference operator making the syntax even clearer:
class BookController { def find = { def findBy = params["findBy"] def appContext = request["foo"] def loggedUser = session["logged_user"] } }
This is one of the ways that Grails unifies access to the different scopes.
class BookController { def find = { def findBy = params.findBy def appContext = request.foo def loggedUser = session.logged_user } }
Using Flash ScopeGrails supports the concept of flash scope is a temporary store for attributes which need to be available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirection, for example:
def delete = { def b = Book.get( params.id ) if(!b) { flash.message = "User not found for id ${params.id}" redirect(action:list) } … // remaining code }
6.1.3 Models and Views
Returning the ModelA model is essentially a map that the view uses when rendering. The keys within that map translate to variable names accessible by the view. There are a couple of ways to return a model. First, you can explicitly return a map instance:
def show = { [ book : Book.get( params.id ) ] }
The above does not reflect what you should use with the scaffolding views - see the scaffolding section for more details.If no explicit model is returned the controller's properties will be used as the model thus allowing you to write code like this:
class BookController { List books List authors def list = { books = Book.list() authors = Author.list() } }
This is possible due to the fact that controllers are prototype scoped. In other words a new controller is created for each request. Otherwise code such as the above would not be thread safe.In the above example the
books and
authors properties will be available in the view.A more advanced approach is to return an instance of the Spring ModelAndView class:
One thing to bear in mind is that certain variable names can not be used in your model:
import org.springframework.web.servlet.ModelAndViewdef index = { def favoriteBooks = … // get some books just for the index page, perhaps your favorites // forward to the list view to show them return new ModelAndView("/book/list", [ bookList : favoriteBooks ]) }
Selecting the ViewIn both of the previous two examples there was no code that specified which view to render. So how does Grails know which view to pick? The answer lies in the conventions. For the action:
Grails will automatically look for a view at the location
class BookController { def show = { [ book : Book.get( params.id ) ] } }
grails-app/views/book/show.gsp (actually Grails will try to look for a JSP first, as Grails can equally be used with JSP).If you wish to render another view, then the render method there to help:
In this case Grails will attempt to render a view at the location
def show = {
def map = [ book : Book.get( params.id ) ]
render(view:"display", model:map)
grails-app/views/book/display.gsp. Notice that Grails automatically qualifies the view location with the
book folder of the
grails-app/views directory. This is convenient, but if you have some shared views you need to access instead use:
In this case Grails will attempt to render a view at the location
def show = {
def map = [ book : Book.get( params.id ) ]
render(view:"/shared/display", model:map)
Rendering a ResponseSometimes its easier (typically with Ajax applications) to render snippets of text or code to the response directly from the controller. For this, the highly flexible
render method can be used:
The above code writes the text "Hello World!" to the response, other examples include:
render "Hello World!"
If you plan on using Groovy's MarkupBuilder to generate html for use with the render method becareful of naming clashes between html elements and Grails tags. e.g.
// write some markup render { for(b in books) { div(id:b.id, b.title) } } // render a specific view render(view:'show') // render a template for each item in a collection render(template:'book_template', collection:Book.list()) // render some text with encoding and content type render(text:"<xml>some xml</xml>",contentType:"text/xml",encoding:"UTF-8")
Will actually call the form tag (which will return some text that will be ignored by the MarkupBuilder). To correctly output a <form> elemement, use the following:
def login = { StringWriter w = new StringWriter() def builder = new groovy.xml.MarkupBuilder(w) builder.html{ head{ title 'Log in' } body{ h1 'Hello' form{ } } } def html = w.toString() render html }
def login = { // … body{ h1 'Hello' builder.form{ } } // … }
6.1.4 Redirects and Chaining
RedirectsActions can be redirected using the redirect method present in all controllers:
Internally the redirect method uses the HttpServletResonse object's
class OverviewController {
def login = {} def find = {
sendRedirect method.The
redirect method expects either:
- Another closure within the same controller class:
// Call the login action within the same class redirect(action:login)
- The name of a controller and action:
// Also redirects to the index action in the home controller redirect(controller:'home',action:'index')
- A URI for a resource relative the application context path:
// Redirect to an explicit URI
- Or a full URL:
Parameters can be optionally passed from one action to the next using the
// Redirect to a URL
params argument of the method:
These parameters are made available through the params dynamic property that also accesses request parameters. If a parameter is specified with the same name as a request parameter the request parameter is overridden and the controller parameter used.Since the
redirect(action:myaction, params:[myparam:"myvalue"])
params object is also a map, you can use it to pass the current request parameters from one action to the next:
Finally, you can also include a fragment in the target URI:
redirect(action:"next", params:params)
will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".
redirect(controller: "test", action: "show", fragment: "profile")
ChainingActions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling the
first action in the below action:
Results in the model:
class ExampleChainController { def first = { chain(action:second,model:[one:1]) } def second = { chain(action:third,model:[two:2]) } def third = { [three:3]) } }
The model can be accessed in subsequent controller actions in the chain via the
[one:1, two:2, three:3]
chainModel map. This dynamic property only exists in actions following the call to the
chain method:
Like the
class ChainController { def nextInChain = { def model = chainModel.myModel … } }
redirect method you can also pass parameters to the
chain method:
chain(action:"action1", model:[one:1], params:[myparam:"param1"])
6.1.5 Controller InterceptorsOften it is useful to intercept processing based on either request, session or application state. This can be achieved via action interceptors. There are currently 2 types of interceptors: before and after.
If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a Filter. Filters can be applied to multiple controllers or URIs, without the need to change the logic of each controller
Before InterceptionThe
beforeInterceptor intercepts processing before the action is executed. If it returns
false then the intercepted action will not be executed. The interceptor can be defined for all actions in a controller as follows:
The above is declared inside the body of the controller definition. It will be executed before all actions and does not interfere with processing. A common use case is however for authentication:
def beforeInterceptor = {
println "Tracing action ${actionUri}"
The above code defines a method called
def beforeInterceptor = [action:this.&auth,except:'login'] // defined as a regular method so its private def auth() { if(!session.user) { redirect(action:'login') return false } } def login = { // display login page }
auth. A method is used so that it is not exposed as an action to the outside world (i.e. it is private). The
beforeInterceptor then defines an interceptor that is used on all actions 'except' the login action and is told to execute the 'auth' method. The 'auth' method is referenced using Groovy's method pointer syntax, within the method itself it detects whether there is a user in the session otherwise it redirects to the login action and returns false, instruction the intercepted action not to be processed.
After InterceptionTo define an interceptor that is executed after an action use the
afterInterceptor property:
The after interceptor takes the resulting model as an argument and can hence perform post manipulation of the model or response.An after interceptor may also modify the Spring MVC ModelAndView object prior to rendering. In this case, the above example becomes:
def afterInterceptor = { model ->
println "Tracing action ${actionUri}"
This allows the view to be changed based on the model returned by the current action. Note that the
def afterInterceptor = { model, modelAndView -> println "Current view is ${modelAndView.viewName}" if(model.someVar) modelAndView.viewName = "/mycontroller/someotherview" println "View is now ${modelAndView.viewName}" }
modelAndView may be
null if the action being intercepted called redirect or render.
Interception ConditionsRails users will be familiar with the authentication example and how the 'except' condition was used when executing the interceptor (interceptors are called 'filters' in Rails, this terminology conflicts with the servlet filter terminology in Java land):
This executes the interceptor for all actions except the specified action. A list of actions can also be defined as follows:
def beforeInterceptor = [action:this.&auth,except:'login']
The other supported condition is 'only', this executes the interceptor for only the specified actions:
def beforeInterceptor = [action:this.&auth,except:['login','register']]
def beforeInterceptor = [action:this.&auth,only:['secure']]
6.1.6 Data BindingData binding is the act of "binding" incoming request parameters onto the properties of an object or an entire graph of objects. Data binding should deal with all necessary type conversion since request parameters, which are typically delivered via a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.Grails uses Spring's underlying data binding capability to perform data binding.
Binding Request Data to the ModelThere are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' implicit constructor:
The data binding happens within the code
def save = {
def b = new Book(params)
new Book(params). By passing the params object to the domain class constructor Grails automatically recognizes that you are trying to bind from request parameters. So if we had an incoming request like:
Then the
title and
author request parameters would automatically get set on the domain class. If you need to perform data binding onto an existing instance then you can use the properties property:
This has exactly the same effect as using the implicit constructor.
def save = { def b = Book.get(params.id) b.properties = params b.save() }
Data binding and Single-ended AssociationsIf you have a
one-to-one or
many-to-one association you can use Grails' data binding capability to update these relationships too. For example if you have an incoming request such as:
Grails will automatically detect the
.id suffix on the request parameter and look-up the
Author instance for the given id when doing data binding such as:
An association property can be set to
def b = new Book(params)
null by passing the literal
String "null". For example:
Data Binding and Many-ended AssociationsIf you have a one-to-many or many-to-many association there are different techniques for data binding depending of the association type.If you have a
Set based association (default for a
hasMany) then the simplest way to populate an association is to simply send a list of identifiers. For example consider the usage of
<g:select> below:
This produces a select box that allows you to select multiple values. In this case if you submit the form Grails will automatically use the identifiers from the select box to populate the
<g:select name="books"
size="5" multiple="yes" optionKey="id"
value="${author?.books}" />
books association.However, if you have a scenario where you want to update the properties of the associated objects the this technique won't work. Instead you have to use the subscript operator:
However, with
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" />
Set based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a
Set has no concept of order, so although we're referring to
books0 and
books1 it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.This is not a problem if you use
List based associations, since a
List has a defined order and an index you can refer to. This is also true of
Map based associations.Note also that if the association you are binding to has a size of 2 and you refer to an element that is outside the size of association:
Then Grails will automatically create a new instance for you at the defined position. If you "skipped" a few elements in the middle:
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[2].title" value="Red Madder" />
Then Grails will automatically create instances in between. For example in the above case Grails will create 4 additional instances if the association being bound had a size of 2.You can bind existing instances of the associated type to a
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[5].title" value="Red Madder" />
List using the same
.id syntax as you would use with a single-ended association. For example:
Would allow individual entries in the
<g:select name="books[0].id" from="${Book.list()}" value="${author?.books[0]?.id}" /> <g:select name="books[1].id" from="${Book.list()}" value="${author?.books[1]?.id}" /> <g:select name="books[2].id" from="${Book.list()}" value="${author?.books[2]?.id}" />
books List to be selected separately.Entries at particular indexes can be removed in the same way too. For example:
Will render a select box that will remove the association at
<g:select name="books[0].id" from="${Book.list()}" value="${author?.books[0]?.id}" noSelection="['null': '']"/>
books0 if the empty option is chosen.Binding to a
Map property works in exactly the same way except that the list index in the parameter name is replaced by the map key:
This would bind the selected image into the
<g:select name="images[cover].id" from="${Image.list()}" value="${book?.images[cover]?.id}" noSelection="['null': '']"/>
Map property
images under a key of
Data binding with Multiple domain classesIt is possible to bind data to multiple domain objects from the params object.For example so you have an incoming request to:
You'll notice the difference with the above request is that each parameter has a prefix such as
author. or
book. which is used to isolate which parameters belong to which type. Grails'
params object is like a multi-dimensional hash and you can index into to isolate only a subset of the parameters to bind.
Notice how we use the prefix before the first dot of the
def b = new Book(params['book'])
book.title parameter to isolate only parameters below this level to bind. We could do the same with an
Author domain class:
def a = new Author(params['author'])
Data binding and type conversion errorsSometimes when performing data binding it is not possible to convert a particular String into a particular target type. What you get is a type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain class. Take this example:
Here we have a domain class
class Book { … URL publisherURL }
Book that uses the Java concrete type
java.net.URL to represent URLs. Now say we had an incoming request such as:
In this case it is not possible to bind the string
a-bad-url to the
publisherURL property os a type mismatch error occurs. You can check for these like this:
Although we have not yet covered error codes (for more information see the section on Validation), for type conversion errors you would want a message to use for the error inside the grails-app/i18n/messages.properties file. You can use a generic error message handler such as:
def b = new Book(params)if(b.hasErrors()) { println "The value ${b.errors.getFieldError('publisherURL').rejectedValue} is not a valid URL!" }
Or a more specific one:
typeMismatch.java.net.URL=The field {0} is not a valid URL
typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL
Data Binding and Security concernsWhen batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes that end up being persisted to the database. You can limit what properties are bound to a given domain class using the subscript operator:
In this case only the
def p = Person.get(1)p.properties['firstName','lastName'] = params
firstName and
lastName properties will be bound.Another way to do this is instead of using domain classes as the target of data binding you could use Command Objects. Alternatively there is also the flexible bindData method.The
bindData method allows the same data binding capability, but to arbitrary objects:
However, the
def p = new Person()
bindData(p, params)
bindData method also allows you to exclude certain parameters that you don't want updated:
Or include only certain properties:
def p = new Person()
bindData(p, params, [exclude:'dateOfBirth'])
def p = new Person()
bindData(p, params, [include:['firstName','lastName]])
6.1.7 XML and JSON Responses
Using the render method to output XMLGrails' supports a few different ways to produce XML and JSON responses. The first one covered is via the render method.The
render method can be passed a block of code to do mark-up building in XML:
The result of this code would be something like:
def list = { def results = Book.list() render(contentType:"text/xml") { books { for(b in results) { book(title:b.title) } } } }
Note that you need to be careful to avoid naming conflicts when using mark-up building. For example this code would produce an error:
<books> <book title="The Stand" /> <book title="The Shining" /> </books>
The reason is that there is local variable
def list = { def books = Book.list() // naming conflict here render(contentType:"text/xml") { books { for(b in results) { book(title:b.title) } } } }
books which Groovy attempts to invoke as a method.
Using the render method to output JSONThe
render method can also be used to output JSON:
In this case the result would be something along the lines of:
def list = { def results = Book.list() render(contentType:"text/json") { books = array { for(b in results) { book title:b.title } } } }
Again the same dangers with naming conflicts apply to JSON building.
[ {title:"The Stand"}, {title:"The Shining"} ]
Automatic XML MarshallingGrails also supports automatic marshaling of domain classes to XML via special converters.To start off with import the
grails.converters package into your controller:
Now you can use the following highly readable syntax to automatically convert domain classes to XML:
import grails.converters.*
The resulting output would look something like the following::
render Book.list() as XML
An alternative to using the converters is to use the codecs feature of Grails. The codecs feature provides encodeAsXML and encodeAsJSON methods:
<?xml version="1.0" encoding="ISO-8859-1"?> <list> <book id="1"> <author>Stephen King</author> <title>The Stand</title> </book> <book id="2"> <author>Stephen King</author> <title>The Shining</title> </book> </list>
For more information on XML marshaling see the section on REST
def xml = Book.list().encodeAsXML() render xml
Automatic JSON MarshallingGrails also supports automatic marshaling to JSON via the same mechanism. Simply substitute
XML with
The resulting output would look something like the following:
render Book.list() as JSON
Again as an alternative you can use the
[ {"id":1, "class":"Book", "author":"Stephen King", "title":"The Stand"}, {"id":2, "class":"Book", "author":"Stephen King", "releaseDate":new Date(1194127343161), "title":"The Shining"} ]
encodeAsJSON to achieve the same effect.
6.1.8 More on JSONBuilderThe previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom implementation specific to Grails.
JSONBuilder and Grails versionsJSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 there deprecated grails.util.JSonBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilderFor backwards compatibility the old
JSonBuilder class is used with the
render method for older applications, if you want to use the newer/better
JSONBuilder class then you can do so by setting the following in
Rendering Simple ObjectsTo render a simple JSON object just set properties within the context of the closure:
The above will produce the JSON:
render(contentType:"text/json") { hello = "world" }
Rendering JSON ArraysTo render a list of objects simple assign a list:
This will produce:
render(contentType:"text/json") {
categories = ['a', 'b', 'c']
You can also render lists of complex objects, for example:
This will produce:
render(contentType:"text/json") { categories = [ { a = "A" }, { b = "B" } ] }
If you want to return a list as the root then you have to use the special
{"categories":[ {"a":"A"} , {"b":"B"}] }
element method:
The above code produces:
render(contentType:"text/json") {
element 1
element 2
element 3
Rendering Complex ObjectsRendering complex objects can be done with closures. For example:
The above will produce the JSON:
render(contentType:"text/json") { categories = ['a', 'b', 'c'] title ="Hello JSON" information = { pages = 10 } }
{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}
Arrays of Complex ObjectsAs mentioned previously you can nest complex objects within arrays using closures:
However, if you need to build them up dynamically then you may want to use the
render(contentType:"text/json") { categories = [ { a = "A" }, { b = "B" } ] }
array method:
def results = Book.list() render(contentType:"text/json") { books = array { for(b in results) { book title:b.title } } }
Direct JSONBuilder API AccessIf you don't have access to the
render method, but still want to produce JSON you can use the API directly:
def builder = new JSONBuilder()def result = builder.build { categories = ['a', 'b', 'c'] title ="Hello JSON" information = { pages = 10 } }// prints the JSON text println result.toString()def sw = new StringWriter() result.render sw
6.1.9 Uploading Files
Programmatic File UploadsGrails supports file uploads via Spring's MultipartHttpServletRequest interface. To upload a file the first step is to create a multipart form like the one below:
There are then a number of ways to handle the file upload. The first way is to work with the Spring MultipartFile instance directly:
Upload Form: <br /> <g:form action="upload" method="post" enctype="multipart/form-data"> <input type="file" name="myFile" /> <input type="submit" /> </g:form>
This is clearly handy for doing transfers to other destinations and manipulating the file directly as you can obtain an InputStream and so on via the MultipartFile interface.
def upload = { def f = request.getFile('myFile') if(!f.empty) { f.transferTo( new File('/some/local/dir/myfile.txt') ) response.sendError(200,'Done'); } else { flash.message = 'file cannot be empty' render(view:'uploadForm') } }
File Uploads through Data BindingFile uploads can also be performed via data binding. For example say you have an
Image domain class as per the below example:
Now if you create an image and pass in the
class Image {
byte[] myFile
params object such as the below example, Grails will automatically bind the file's contents as a byte to the
myFile property:
It is also possible to set the contents of the file as a string by changing the type of the
def img = new Image(params)
myFile property on the image to a String type:
class Image {
String myFile
6.1.10 Command ObjectsGrails controllers support the concept of command objects. A command object is similar to a form bean in something like Struts and they are useful in circumstances when you want to populate a subset of the properties needed to update a domain class. Or where there is no domain class required for the interaction, but you need features such as data binding and validation.
Declaring Command ObjectsCommand objects are typically declared in the same source file as a controller directly below the controller class definition. For example:
As the previous example demonstrates you can supply constraints to command objects just as you can with domain classes.
class UserController { … } class LoginCommand { String username String password static constraints = { username(blank:false, minSize:6) password(blank:false, minSize:6) } }
Using Command ObjectsTo use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create, populate and validate.Before the controller action is executed Grails will automatically create an instance of the command object class, populate the properties of the command object with request parameters having corresponding names and the command object will be validated. For Example:
class LoginController { def login = { LoginCommand cmd -> if(cmd.hasErrors()) { redirect(action:'loginForm') } else { // do something else } } }
Command Objects and Dependency InjectionCommand objects can participate in dependency injection. This is useful if your command object has some custom validation logic which may need to interact with Grails services:
In this example the command object interacts with a bean injected by name from the Spring
class LoginCommand { def loginService String username String password static constraints = { username validator: { val, obj -> obj.loginService.canLogin(obj.username, obj.password) } } }
6.1.11 Handling Duplicate Form SubmissionsGrails has built in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you need to define a token on the form tag:
Then in your controller code you can use the withForm method to handle valid and invalid requests:
<g:form useToken="true" ...>
If you only provide the withForm method and not the chained
withForm { // good request }.invalidToken { // bad request }
invalidToken method then by default Grails will store the invalid token in a
flash.invalidToken variable and redirect the request back to the original page. This can then be checked in the view:
<g:if test="${flash.invalidToken}"> Don't click the button twice! </g:if>
The withForm tag makes use of the session and hence requires session affinity if used in a cluster.
6.1.12 Simple Type Converters
Type Conversion MethodsIf you prefer to avoid the overhead of Data Binding and simply want to convert incoming parameters (typically Strings) into another more appropriate type the params object has a number of convenience methods for each type:
The above example uses the
def total = params.int('total')
int method, there are also methods for
short and so on. Each of these methods are null safe and safe from any parsing errors so you don't have to perform any addition checks on the parameters.These same type conversion methods are also available on the
attrs parameter of GSP tags.
Handling Multi ParametersA common use case is dealing with multiple request parameters of the same name. For example you could get a query string such as
?name=Bob&name=Judy.In this case dealing with 1 parameter and dealing with many has different semantics since Groovy's iteration mechanics for
String iterate over each character. To avoid this problem the params object provides a
list method that always returns a list:
for(name in params.list('name')) {
println name
6.2 Groovy Server PagesGroovy Servers Pages (or GSP for short) is Grails' view technology. It is designed to be familiar for users of technologies such as ASP and JSP, but to be far more flexible and intuitive.In Grails GSPs live in the
grails-app/views directory and are typically rendered automatically (by convention) or via the render method such as:
A GSP is typically a mix of mark-up and GSP tags which aid in view rendering.
Although it is possible to have Groovy logic embedded in your GSP and doing this will be covered in this document the practice is strongly discouraged. Mixing mark-up and code is a bad thing and most GSP pages contain no code and needn't do so.A GSP typically has a "model" which is a set of variables that are used for view rendering. The model is passed to the GSP view from a controller. For example consider the following controller action:
This action will look-up a
def show = { [book: Book.get(params.id)] }
Book instance and create a model that contains a key called
book. This key can then be reference within the GSP view using the name
6.2.1 GSP BasicsIn the next view sections we'll go through the basics of GSP and what is available to you. First off let's cover some basic syntax that users of JSP and ASP should be familiar with.GSP supports the usage of
<% %> blocks to embed Groovy code (again this is discouraged):
As well as this syntax you can also use the
<html> <body> <% out << "Hello GSP!" %> </body> </html>
<%= %> syntax to output values:
GSP also supports JSP-style server-side comments as the following example demonstrates:
<html> <body> <%="Hello GSP!" %> </body> </html>
<html> <body> <%-- This is my comment --%> <%="Hello GSP!" %> </body> </html>
188.8.131.52 Variables and ScopesWithin the
<% %> brackets you can of course declare variables:
And then re-use those variables further down the page:
<% now = new Date() %>
However, within the scope of a GSP there are a number of pre-defined variables including:
application- The javax.servlet.ServletContext instance
applicationContextThe Spring ApplicationContext instance
flash- The flash object
grailsApplication- The GrailsApplication instance
out- The response writer for writing to the output stream
params- The params object for retrieving request parameters
request- The HttpServletRequest instance
response- The HttpServletResponse instance
session- The HttpSession instance
webRequest- The GrailsWebRequest instance
22.214.171.124 Logic and IterationUsing the
<% %> syntax you can of course embed loops and so on using this syntax:
As well as logical branching:
<html> <body> <% [1,2,3,4].each { num -> %> <p><%="Hello ${num}!" %></p> <%}%> </body> </html>
<html> <body> <% if(params.hello == 'true' )%> <%="Hello!"%> <% else %> <%="Goodbye!"%> </body> </html>
220.127.116.11 Page DirectivesGSP also supports a few JSP-style page directives.The import directive allows you to import classes into the page. However, it is rarely needed due to Groovy's default imports and GSP Tags:
GSP also supports the contentType directive:
<%@ page import="java.awt.*" %>
The contentType directive allows using GSP to render other formats.
<%@ page contentType="text/json" %>
18.104.22.168 ExpressionsIn GSP the
<%= %> syntax introduced earlier is rarely used due to the support for GSP expressions. It is present mainly to allow ASP and JSP developers to feel at home using GSP. A GSP expression is similar to a JSP EL expression or a Groovy GString and takes the form
However, unlike JSP EL you can have any Groovy expression within the
<html> <body> Hello ${params.name} </body> </html>
${..} parenthesis. Variables within the
${..} are not escaped by default, so any HTML in the variable's string is output directly to the page. To reduce the risk of Cross-site-scripting (XSS) attacks, you can enable automatic HTML escaping via the
grails.views.default.codec setting in
Other possible values are 'none' (for no default encoding) and 'base64'.
6.2.2 GSP TagsNow that the less attractive JSP heritage has been set aside, the following sections cover GSP's built-in tags, which are the favored way to define GSP pages.
The section on Tag Libraries covers how to add your own custom tag libraries.All built-in GSP tags start with the prefix
g:. Unlike JSP, you don't need to specify any tag library imports. If a tag starts with
g: it is automatically assumed to be a GSP tag. An example GSP tag would look like:
GSP tags can also have a body such as:
<g:example />
Expressions can be passed into GSP tag attributes, if an expression is not used it will be assumed to be a String value:
<g:example> Hello world </g:example>
Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:
<g:example attr="${new Date()}"> Hello world </g:example>
Note that within the values of attributes you must use single quotes for Strings:
<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]"> Hello world </g:example>
With the basic syntax out the way, the next sections look at the tags that are built into Grails by default.
<g:example attr="${new Date()}" attr2="[one:'one', two:'two']"> Hello world </g:example>
188.8.131.52 Variables and ScopesVariables can be defined within a GSP using the set tag:
Here we assign a variable called
<g:set var="now" value="${new Date()}" />
now to the result of a GSP expression (which simply constructs a new
java.util.Date instance). You can also use the body of the
<g:set> tag to define a variable:
Variables can also be placed in one of the following scopes:
<g:set var="myHTML"> Some re-usable code on: ${new Date()} </g:set>
page- Scoped to the current page (default)
request- Scoped to the current request
flash- Placed within flash scope and hence available for the next request
session- Scoped for the user session
application- Application-wide scope.
scope attribute:
<g:set var="now" value="${new Date()}" scope="request" />
220.127.116.11 Logic and IterationGSP also supports logical and iterative tags out of the box. For logic there are if, else and elseif which support your typical branching scenarios:
For iteration GSP has the each and while tags:
<g:if test="${session.role == 'admin'}"> <%-- show administrative functions --%> </g:if> <g:else> <%-- show basic functions --%> </g:else>
<g:each in="${[1,2,3]}" var="num"> <p>Number ${num}</p> </g:each><g:set var="num" value="${1}" /> <g:while test="${num < 5 }"> <p>Number ${num++}</p> </g:while>
220.127.116.11 Search and FilteringIf you have collections of objects you often need to sort and filter them in some way. GSP supports the findAll and grep for this task:
Stephen King's Books: <g:findAll in="${books}" expr="it.author == 'Stephen King'"> <p>Title: ${it.title}</p> </g:findAll>
expr attribute contains a Groovy expression that can be used as a filter. Speaking of filters the grep tag does a similar job such as filter by class:
Or using a regular expression:
<g:grep in="${books}" filter="NonFictionBooks.class"> <p>Title: ${it.title}</p> </g:grep>
The above example is also interesting due to its usage of GPath. GPath is Groovy's equivalent to an XPath like language. Essentially the
<g:grep in="${books.title}" filter="~/.*?Groovy.*?/"> <p>Title: ${it}</p> </g:grep>
books collection is a collection of
Book instances. However assuming each
Book has a
title, you can obtain a list of Book titles using the expression
books.title. Groovy will auto-magically go through the list of Book instances, obtain each title, and return a new list!
184.108.40.206 Links and ResourcesGSP also features tags to help you manage linking to controllers and actions. The link tag allows you to specify controller and action name pairing and it will automatically work out the link based on the URL Mappings, even if you change them! Some examples of the link can be seen below:
<g:link action="show" id="1">Book 1</g:link> <g:link action="show" id="${currentBook.id}">${currentBook.name}</g:link> <g:link controller="book">Book Home</g:link> <g:link controller="book" action="list">Book List</g:link> <g:link url="[action:'list',controller:'book']">Book List</g:link> <g:link action="list" params="[sort:'title',order:'asc',author:currentBook.author]"> Book List </g:link>
220.127.116.11 Forms and Fields
Form BasicsGSP supports many different tags for aiding in dealing with HTML forms and fields, the most basic of which is the form tag. The
form tag is a controller/action aware version of the regular HTML form tag. The
url attribute allows you to specify which controller and action to map to:
In this case we create a form called
<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>
myForm that submits to the
list action. Beyond that all of the usual HTML attributes apply.
Form FieldsAs well as easy construction of forms GSP supports custom tags for dealing with different types of fields including:
- textField - For input fields of type 'text'
- checkBox - For input fields of type 'checkbox'
- radio - For input fields of type 'radio'
- hiddenField - For input fields of type 'hidden'
- select - For dealing with HTML select boxes
GSP also contains extended helper versions of the above tags such as radioGroup (for creating groups of radio tags), localeSelect, currencySelect and timeZoneSelect (for selecting locale's, currencies and time zone's respectively).
<g:textField name="myField" value="${myValue}" />
Multiple Submit ButtonsThe age old problem of dealing with multiple submit buttons is also handled elegantly with Grails via the actionSubmit tag. It is just like a regular submit, but allows you to specify an alternative action to submit to:
<g:actionSubmit value="Some update label" action="update" />
18.104.22.168 Tags as Method CallsOne major different between GSP tags and other tagging technologies is that GSP tags can be called as either regular tags or as method calls from either controllers, tag libraries or GSP views.
Tags as method calls from GSPsWhen called as methods tags return their results as a String instead of writing directly to the response. So for example the createLinkTo tag can equally be called as a method:
This is particularly useful when you need to use a tag within an attribute:
Static Resource: ${createLinkTo(dir:"images", file:"logo.jpg")}
In view technologies that don't support this feature you have to nest tags within tags, which becomes messy quickly and often has an adverse effect of WYSWIG tools such as Dreamweaver that attempt to render the mark-up as it is not well-formed:
<img src="${createLinkTo(dir:'images', file:'logo.jpg')}" />
<img src="<g:createLinkTo dir="images" file="logo.jpg" />" />
Tags as method calls from Controllers and Tag LibrariesYou can also invoke tags from controllers and tag libraries. Tags within the default
g: namespace can be invoked without the prefix and a String result is returned:
However, you can also prefix the namespace to avoid naming conflicts:
def imageLocation = createLinkTo(dir:"images", file:"logo.jpg")
If you have a custom namespace you can use that prefix instead (Example using the FCK Editor plugin):
def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg")
def editor = fck.editor()
6.2.3 Views and TemplatesAs well as views, Grails has the concept of templates. Templates are useful for separating out your views into maintainable chunks and combined with Layouts provide a highly re-usable mechanism for structure views.
Template BasicsGrails uses the convention of placing an underscore before the name of a view to identify it as a template. For example a you may have a template that deals with rendering Books located at
To render this template from one of the views in
<div class="book" id="${book?.id}"> <div>Title: ${book?.title}</div> <div>Author: ${book?.author?.name}</div> </div>
grails-app/views/book you can use the render tag:
Notice how we pass into a model to use using the
<g:render template="bookTemplate" model="[book:myBook]" />
model attribute of the render tag. If you have multiple
Book instances you can also render the template for each
Book using the render tag:
<g:render template="bookTemplate" var="book" collection="${bookList}" />
Shared TemplatesIn the previous example we had a template that was specific to the
BookController and its views at
grails-app/views/book. However, you may want to share templates across your application.In this case you can place them in the root views directory at grails-app/views or any subdirectory below that location and then with the template attribute use a
/ before the template name to indicate the relative template path. For example if you had a template called
grails-app/views/shared/_mySharedTemplate.gsp, you could reference it as follows:
You can also use this technique to reference templates in any directory from any view or controller:
<g:render template="/shared/mySharedTemplate" />
<g:render template="/book/bookTemplate" model="[book:myBook]" />
The Template NamespaceSince templates are used so frequently there is template namespace, called
tmpl, available that makes using templates easier. Consider for example the following usage pattern:
This can be expressed with the
<g:render template="bookTemplate" model="[book:myBook]" />
tmpl namespace as follows:
<tmpl:bookTemplate book="${myBook}" />
Templates in Controllers and Tag LibrariesYou can also render templates from controllers using the render method found within controllers, which is useful for Ajax applications:
The render method within controllers writes directly to the response, which is the most common behaviour. If you need to instead obtain the result of template as a String you can use the render tag:
def show = {
def b = Book.get(params.id)
render(template:"bookTemplate", model:[book:b])
Notice the usage of the
def show = { def b = Book.get(params.id) String content = g.render(template:"bookTemplate", model:[book:b]) render content }
g. namespace which tells Grails we want to use the tag as method call instead of the render method.
6.2.4 Layouts with Sitemesh
Creating LayoutsGrails leverages Sitemesh, a decorator engine, to support view layouts. Layouts are located in the
grails-app/views/layouts directory. A typical layout can be seen below:
The key elements are the layoutHead, layoutTitle and layoutBody tag usages, here is what they do:
<html> <head> <title><g:layoutTitle default="An example decorator" /></title> <g:layoutHead /> </head> <body onload="${pageProperty(name:'body.onload')}"> <div class="menu"><!--my common menu goes here--></menu> <div class="body"> <g:layoutBody /> </div> </div> </body> </html>
layoutTitle- outputs the target page's title
layoutHead- outputs the target pages head tag contents
layoutBody- outputs the target pages body tag contents
Triggering LayoutsThere are a few ways to trigger a layout. The simplest is to add a meta tag to the view:
In this case a layout called
<html> <head> <title>An Example Page</title> <meta name="layout" content="main"></meta> </head> <body>This is my content!</body> </html>
grails-app/views/layouts/main.gsp will be used to layout the page. If we were to use the layout from the previous section the output would resemble the below:
<html> <head> <title>An Example Page</title> </head> <body onload=""> <div class="menu"><!--my common menu goes here--></div> <div class="body"> This is my content! </div> </body> </html>
Specifying A Layout In A ControllerAnother way to specify a layout is to specify the name of the layout by assigning a value to the "layout" property in a controller. For example, if you have a controller such as:
You can create a layout called
class BookController {
static layout = 'customer' def list = { … }
grails-app/views/layouts/customer.gsp which will be applied to all views that the
BookController delegates to. The value of the "layout" property may contain a directory structure relative to the
grails-app/views/layouts/ directory. For example:
Views rendered from that controller would be decorated with the
class BookController {
static layout = 'custom/customer' def list = { … }
grails-app/views/layouts/custom/customer.gsp template.
Layout by ConventionAnother way to associate layouts is to use "layout by convention". For example, if you have a controller such as:
You can create a layout called
class BookController { def list = { … } }
grails-app/views/layouts/book.gsp, by convention, which will be applied to all views that the
BookController delegates to.Alternatively, you can create a layout called
grails-app/views/layouts/book/list.gsp which will only be applied to the
list action within the
BookController.If you have both the above mentioned layouts in place the layout specific to the action will take precedence when the list action is executed.If a layout may not be located using any of those conventions, the convention of last resort is to look for the application default layout which
grails-app/views/layouts/application.gsp. The name of the application default layout may be changed by defining a property
grails-app/conf/Config.groovy as follows:
With that property in place, the application default layout will be
// grails-app/conf/Config.groovy
Inline LayoutsGrails' also supports Sitemesh's concept of inline layouts with the applyLayout tag. The
applyLayout tag can be used to apply a layout to a template, URL or arbitrary section of content. Essentially, this allows to even further modularize your view structure by "decorating" your template includes.Some examples of usage can be seen below:
<g:applyLayout name="myLayout" template="bookTemplate" collection="${books}" /><g:applyLayout name="myLayout" url="http://www.google.com" /><g:applyLayout name="myLayout"> The content to apply a layout to </g:applyLayout>
Server-Side IncludesWhile the applyLayout tag is useful for applying layouts to external content, if you simply want to include external content in the current page you can do so with the include:
You can even combine the include tag and the applyLayout tag for added flexibility:
<g:include controller="book" action="list"></g:include>
Finally, you can also call the include tag from a controller or tag library as a method:
<g:applyLayout name="myLayout"> <g:include controller="book" action="list"></g:include> </g:applyLayout>
The resulting content will be provided via the return value of the include tag.
def content = include(controller:"book", action:"list")
6.2.5 Sitemesh Content BlocksAlthough it is useful to decorate an entire page sometimes you may find the need to decorate independent sections of your site. To do this you can use content blocks. To get started you need to divide the page to be decorate using the
<content> tag:
Then within the layout you can reference these components and apply individual layouts to each:
<content tag="navbar"> … draw the navbar here… </content> <content tag="header"> … draw the header here… </content> <content tag="footer"> … draw the footer here… </content> <content tag="body"> … draw the body here… </content>
<html> <body> <div id="header"> <g:applyLayout name="headerLayout"> <g:pageProperty name="page.header" /> </g:applyLayout> </div> <div id="nav"> <g:applyLayout name="navLayout"> <g:pageProperty name="page.navbar" /> </g:applyLayout> </div> <div id="body"> <g:applyLayout name="bodyLayout"> <g:pageProperty name="page.body" /> </g:applyLayout> </div> <div id="footer"> <g:applyLayout name="footerLayout"> <g:pageProperty name="page.footer" /> </g:applyLayout> </div> </body> </html>
6.2.6 Making Changes to a Deployed ApplicationOne of the main issues with deploying a Grails application (or typically any servlet-based one) is that any change to the views requires you to redeploy your whole application. If all you want to do is fix a typo on a page, or change an image link, it can seem like a lot of unnecessary work. For such simple requirements, Grails does have a solution: the
grails.gsp.view.dir configuration setting.How does this work? The first step is to decide where the GSP files should go. Let's say we want to keep them unpacked in a
/var/www/grails/my-app directory. We add these two lines to
grails-app/conf/Config.groovy :
The first line tells Grails that modified GSP files should be reloaded at runtime. If you don't have this setting, you can make as many changes as you like but they won't be reflected in the running application. The second line tells Grails where to load the views and layouts from.
grails.gsp.enable.reload = true grails.gsp.view.dir = "/var/www/grails/my-app/"
The trailing slash on the Setting "grails.gsp.view.dir" is optional. If it's not specified, you can update files directly to the application server's deployed war directory. Depending on the application server, these files might get overwritten when the server is restarted. Most application servers support "exploded war deployment" which is recommended in this case.With those settings in place, all you need to do is copy the views from your web application to the external directory. On a Unix-like system, this would look something like this:
grails.gsp.view.dir value is important! Without it, Grails will look for views in the parent directory.
The key point here is that you must retain the view directory structure, including the
mkdir -p /var/www/grails/my-app/grails-app/views cp -R grails-app/views/* /var/www/grails/my-app/grails-app/views
grails-app/views bit. So you end up with the path
/var/www/grails/my-app/grails-app/views/... .One thing to bear in mind with this technique is that every time you modify a GSP, it uses up permgen space. So at some point you will eventually hit "out of permgen space" errors unless you restart the server. So this technique is not recommended for frequent or large changes to the views.There are also some System properties to control GSP reloading:
|altervative system property for enabling the GSP reload mode without changing Config.groovy
|interval between checking the lastmodified time of the gsp source file, unit is milliseconds
|the number of milliseconds leeway to give before deciding a file is out of date. this is needed because different roundings usually cause a 1000ms difference in lastmodified times
6.2.7 GSP Debugging
Viewing the generated source code
- Adding "?showSource=true" or "&showSource=true" to the url shows the generated groovy source code for the view instead of rendering it. It won't show the source code of included templates. This only works in development mode
- The saving of all generated source code can be activated by setting the property "grails.views.gsp.keepgenerateddir" (in Config.groovy) . It should point to a directory that's existing and writable.
- During "grails war" gsp pre-compilation, the generated source code is stored in grails.project.work.dir/gspcompile (usually in ~/.grails/(grails_version)/projects/(project name)/gspcompile).
Debugging GSP code with a debugger
Viewing information about templates used to render a single urlGSP templates are re-used in large web applications by using the g:render taglib. A lot of small templates can be used to render a single page. It might be hard to find out what gsp template actually renders the html seen in the result. The debug templates -feature adds html comments to the output. The comments contain debug information about gsp templates used to render the page.Usage is simple: append "?debugTemplates" or "&debugTemplates" to the url and view the source of the result in your browser. "debugTemplates" is restricted to development mode. It won't work in production.Here is an example of comments added by debugTemplates :
Each comment block has a unique id so that you can find the start & end of each template call.
<!-- GSP #2 START template: /home/user/sampleapp/grails-app/views/_carousel.gsp precompiled: false lastmodified: 22.6.2010 10:45 -->
<!-- GSP #2 END template: /home/user/sampleapp/grails-app/views/_carousel.gsp rendering time: 115 ms -->
6.3 Tag LibrariesLike Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails tag library mechanism is simply, elegant and completely reloadable at runtime.Quite simply, to create a tag library create a Groovy class that ends with the convention
TagLib and place it within the
grails-app/taglib directory:
Now to create a tag simply create property that is assigned a block of code that takes two arguments: The tag attributes and the body content:
class SimpleTagLib {}
class SimpleTagLib { def simple = { attrs, body -> } }
attrs argument is a simple map of the attributes of the tag, whilst the
body argument is another invokable block of code that returns the body content:
As demonstrated above there is an implicit
class SimpleTagLib { def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }
out variable that refers to the output
Writer which you can use to append content to the response. Then you can simply reference the tag inside your GSP, no imports necessary:
<g:emoticon happy="true">Hi John</g:emoticon>
To help IDEs like SpringSource Tool Suite (STS) and others autocomplete tag attributes, you should add Javadoc comments to your tag closures with
@attrdescriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.For example:and any mandatory attributes should include the REQUIRED keyword, e.g.class SimpleTagLib { /** * Renders the body with an emoticon. * * @attr happy whether to show a happy emoticon ('true') or a sad emoticon ('false') */ def emoticon = { attrs, body -> out << body() << (attrs.happy == 'true' ? " :-)" : " :-(") } }class SimpleTagLib { /** * Creates a new password field. * * @attr name REQUIRED the field name * @attr value the field value */ def passwordField = { attrs -> attrs.type = "password" attrs.tagName = "passwordField" fieldImpl(out, attrs) } }
6.3.1 Variables and ScopesWithin the scope of a tag library there are a number of pre-defined variables including:
actionName- The currently executing action name
controllerName- The currently executing controller name
flash- The flash object
grailsApplication- The GrailsApplication instance
out- The response writer for writing to the output stream
pageScope- A reference to the pageScope object used for GSP rendering (i.e. the binding)
params- The params object for retrieving request parameters
pluginContextPath- The context path to the plugin that contains the tag library
request- The HttpServletRequest instance
response- The HttpServletResponse instance
servletContext- The javax.servlet.ServletContext instance
session- The HttpSession instance
6.3.2 Simple TagsAs demonstrated it the previous example it is trivial to write simple tags that have no body and merely output content. Another example is a
dateFormat style tag:
The above uses Java's
def dateFormat = { attrs, body ->
out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)
SimpleDateFormat class to format a date and then write it to the response. The tag can then be used within a GSP as follows:
With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:
<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />
Although this approach may be tempting it is not very clean. A better approach would be to re-use the render tag:
def formatBook = { attrs, body -> out << "<div id="${attrs.book.id}">" out << "Title : ${attrs.book.title}" out << "</div>" }
And then have a separate GSP template that does the actual rendering.
def formatBook = { attrs, body ->
out << render(template:"bookTemplate", model:[book:attrs.book])
6.3.3 Logical TagsYou can also create logical tags where the body of the tag is only output once a set of conditions have been met. An example of this may be a set of security tags:
The tag above checks if the user is an administrator and only outputs the body content if he/she has the correct set of access privileges:
def isAdmin = { attrs, body -> def user = attrs['user'] if(user != null && checkUserPrivs(user)) { out << body() } }
<g:isAdmin user="${myUser}"> // some restricted content </g:isAdmin>
6.3.4 Iterative TagsIterative tags are trivial too, since you can invoke the body multiple times:
In this example we check for a
def repeat = { attrs, body -> attrs.times?.toInteger().times { num -> out << body(num) } }
times attribute and if it exists convert it to a number then use Groovy's
times method to iterate by the number of times specified by the number:
Notice how in this example we use the implicit
<g:repeat times="3"> <p>Repeat this 3 times! Current repeat = ${it}</p> </g:repeat>
it variable to refer to the current number. This works because when we invoked the body we passed in the current value inside the iteration:
That value is then passed as the default variable
out << body(num)
it to the tag. However, if you have nested tags this can lead to conflicts, hence you should should instead name the variables that the body uses:
Here we check if there is a
def repeat = { attrs, body -> def var = attrs.var ? attrs.var : "num" attrs.times?.toInteger().times { num -> out << body((var):num) } }
var attribute and if there is use that as the name to pass into the body invocation on this line:
out << body((var):num)
Note the usage of the parenthesis around the variable name. If you omit these Groovy assumes you are using a String key and not referring to the variable itself.Now we can change the usage of the tag as follows:
Notice how we use the
<g:repeat times="3" var="j"> <p>Repeat this 3 times! Current repeat = ${j}</p> </g:repeat>
var attribute to define the name of the variable
j and then we are able to reference that variable within the body of the tag.
6.3.5 Tag NamespacesBy default, tags are added to the default Grails namespace and are used with the
g: prefix in GSP pages. However, you can specify a different namespace by adding a static property to your
TagLib class:
Here we have specified a
class SimpleTagLib { static namespace = "my" def example = { attrs -> … } }
namespace of
my and hence the tags in this tag lib must then be referenced from GSP pages like this:
Where the prefix is the same as the value of the static
<my:example name="..." />
namespace property. Namespaces are particularly useful for plugins.
Tags within namespaces can be invoked as methods using the namespace as a prefix to the method call:
This works from GSP, controllers or tag libraries
out << my.example(name:"foo")
6.3.6 Using JSP Tag LibrariesIn addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP. To do so simply declare the JSP you want to use via the
taglib directive:
Then you can use it like any other tag:
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
With the added bonus that you can invoke JSP tags like methods:
<fmt:formatNumber value="${10}" pattern=".00"/>
${fmt.formatNumber(value:10, pattern:".00")}
6.3.7 Tag return valueSince Grails 1.2, a tag library call returns an instance of
org.codehaus.groovy.grails.web.util.StreamCharBuffer class by default.
This change improves performance by reducing object creation and optimizing buffering during request processing.
In earlier Grails versions, a
java.lang.String instance was returned.Tag libraries can also return direct object values to the caller since Grails 1.2..
Object returning tag names are listed in a static
returnObjectForTags property in the tag library class.Example:
class ObjectReturningTagLib { static namespace = "cms" static returnObjectForTags = ['content'] def content = { attrs, body -> CmsContent.findByCode(attrs.code)?.content } }
6.4 URL MappingsThroughout the documentation so far the convention used for URLs has been the default of
/controller/action/id. However, this convention is not hard wired into Grails and is in fact controlled by a URL Mappings class located at
UrlMappings class contains a single property called
mappings that has been assigned a block of code:
class UrlMappings {
static mappings = {
6.4.1 Mapping to Controllers and ActionsTo create a simple mapping simply use a relative URL as the method name and specify named parameters for the controller and action to map to:
In this case we've mapped the URL
"/product"(controller:"product", action:"list")
/product to the
list action of the
ProductController. You could of course omit the action definition to map to the default action of the controller:
An alternative syntax is to assign the controller and action to use within a block passed to the method:
Which syntax you use is largely dependent on personal preference. If you simply want to rewrite on URI onto another explicit URI (rather than a controller/action pair) this can be achieved with the following example:
"/product" { controller = "product" action = "list" }
Rewriting specific URIs is often useful when integrating with other frameworks.
6.4.2 Embedded Variables
Simple VariablesThe previous section demonstrated how to map trivial URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash / character. A concrete token is one which is well defined such as as
/product. However, in many circumstances you don't know what the value of a particular token will be until runtime. In this case you can use variable placeholders within the URL for example:
In this case by embedding a $id variable as the second token Grails will automatically map the second token into a parameter (available via the params object) called
static mappings = { "/product/$id"(controller:"product") }
id. For example given the URL
/product/MacBook, the following code will render "MacBook" to the response:
You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:
class ProductController { def index = { render params.id } }
The above mapping would allow you to do things like:
static mappings = { "/$blog/$year/$month/$day/$id"(controller:"blog", action:"show") }
The individual tokens in the URL would again be mapped into the params object with values available for
id and so on.
Dynamic Controller and Action NamesVariables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:
Here the name of the controller, action and id are implicitly obtained from the variables
static mappings = { "/$controller/$action?/$id?"() }
action and
id embedded within the URL.You can also resolve the controller name and action name to execute dynamically using a closure:
static mappings = { "/$controller" { action = { params.goHere } } }
Optional VariablesAnother characteristic of the default mapping is the ability to append a
? at the end of a variable to make it an optional token. In a further example this technique could be applied to the blog URL mapping to have more flexible linking:
With this mapping all of the below URLs would match with only the relevant parameters being populated in the params object:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
/graemerocher/2007/01/10/my_funky_blog_entry /graemerocher/2007/01/10 /graemerocher/2007/01 /graemerocher/2007 /graemerocher
Arbitrary VariablesYou can also pass arbitrary parameters from the URL mapping into the controller by merely setting them in the block passed to the mapping:
This variables will be available within the params object passed to the controller.
"/holiday/win" { id = "Marrakech" year = 2007 }
Dynamically Resolved VariablesThe hard coded arbitrary variables are useful, but sometimes you need to calculate the name of the variable based on runtime factors. This is also possible by assigning a block to the variable name:
In the above case the code within the blocks is resolved when the URL is actually matched and hence can be used in combination with all sorts of logic.
"/holiday/win" { id = { params.id } isEligible = { session.user != null } // must be logged in }
6.4.3 Mapping to ViewsIf you want to resolve a URL to a view, without a controller or action involved, you can do so too. For example if you wanted to map the root URL
/ to a GSP at the location
grails-app/views/index.gsp you could use:
Alternatively if you need a view that is specific to a given controller you could use:
static mappings = { "/"(view:"/index") // map the root URL }
static mappings = { "/help"(controller:"site",view:"help") // to a view for a controller }
6.4.4 Mapping to Response CodesGrails also allows you to map HTTP response codes to controllers, actions or views. All you have to do is use a method name that matches the response code you are interested in:
Or alternatively if you merely want to provide custom error pages:
static mappings = { "403"(controller: "errors", action: "forbidden") "404"(controller: "errors", action: "notFound") "500"(controller: "errors", action: "serverError") }
static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(view: "/errors/serverError") }
Declarative Error HandlingIn addition you can configure handlers for individual exceptions:
With this configuration, an
static mappings = { "403"(view: "/errors/forbidden") "404"(view: "/errors/notFound") "500"(controller: "errors", action: "illegalArgument", exception: IllegalArgumentException) "500"(controller: "errors", action: "nullPointer", exception: NullPointerException) "500"(controller: "errors", action: "customException", exception: MyException) "500"(view: "/errors/serverError") }
IllegalArgumentException will be handled by the
illegalArgument action in
ErrorsController, a
NullPointerException will be handled by the
nullPointer action, and a
MyException will be handled by the
customException action. Other exceptions will be handled by the catch-all rule and use the
/errors/serverError view.You can access the exception from your custom error handing view or controller action via the request's
exception attribute like so:
class ErrorController { def handleError = { def exception = request.exception // perform desired processing to handle the exception } }
If your error-handling controller action throws an exception as well, you'll end up with a
6.4.5 Mapping to HTTP methodsURL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is extremely useful for RESTful APIs and for restricting mappings based on HTTP method.As an example the following mappings provide a RESTful API URL mappings for the
static mappings = { "/product/$id"(controller:"product"){ action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] } }
6.4.6 Mapping WildcardsGrails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:
This mapping will match all paths to images such as
static mappings = { "/images/*.jpg"(controller:"image") }
/image/logo.jpg. Of course you can achieve the same effect with a variable:
However, you can also use double wildcards to match more than one level below:
static mappings = { "/images/$name.jpg"(controller:"image") }
In this cases the mapping will match
static mappings = { "/images/**.jpg"(controller:"image") }
/image/logo.jpg as well as
/image/other/logo.jpg. Even better you can use a double wildcard variable:
In this case it will store the path matched by the wildcard inside a
static mappings = { // will match /image/logo.jpg and /image/other/logo.jpg "/images/$name**.jpg"(controller:"image") }
name parameter obtainable from the params object:
If you are using wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping process. To do this you can provide an
def name = params.name println name // prints "logo" or "other/logo"
excludes setting inside the
UrlMappings.groovy class:
In this case Grails won't attempt to match any URIs that start with
class UrlMappings = { static excludes = ["/images/*", "/css/*"] static mappings = { … } }
/images or
6.4.7 Automatic Link Re-WritingAnother great feature of URL mappings is that they automatically customize the behaviour of the link tag so that changing the mappings don't require you to go and change all of your links.This is done through a URL re-writing technique that reverse engineers the links from the URL mappings. So given a mapping such as the blog one from an earlier section:
If you use the link tag as follows:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
Grails will automatically re-write the URL in the correct format:
<g:link controller="blog" action="show" params="[blog:'fred', year:2007]">My Blog</g:link> <g:link controller="blog" action="show" params="[blog:'fred', year:2007, month:10]">My Blog - October 2007 Posts</g:link>
<a href="/fred/2007">My Blog</a> <a href="/fred/2007/10">My Blog - October 2007 Posts</a>
6.4.8 Applying ConstraintsURL Mappings also support Grails' unified validation constraints mechanism, which allows you to further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:
This allows URLs such as:
static mappings = { "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show") }
However, it would also allow:
This is problematic as it forces you to do some clever parsing in the controller code. Luckily, URL Mappings can be constrained to further validate the URL tokens:
In this case the constraints ensure that the
"/$blog/$year?/$month?/$day?/$id?" { controller = "blog" action = "show" constraints { year(matches:/\d{4}/) month(matches:/\d{2}/) day(matches:/\d{2}/) } }
month and
day parameters match a particular valid pattern thus relieving you of that burden later on.
6.4.9 Named URL MappingsURL Mappings also support named mappings. Simply put, named mappings are mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are being generated.The syntax for defining a named mapping is as follows:
An example:
static mappings = {
name <mapping name>: <url pattern> {
// …
The mapping may be referenced in a link tag in a GSP.
static mappings = { name personList: "/showPeople" { controller = 'person' action = 'list' } name accountDetails: "/details/$acctNumber" { controller = 'product' action = 'accountDetails' } }
That would result in:
<g:link mapping="personList">List People</g:link>
Parameters may be specified using the params attribute.
<a href="/showPeople">List People</a>
That would result in:
<g:link mapping="accountDetails" params="[acctNumber:'8675309']">Show Account</g:link>
Alternatively you may reference a named mapping using the link namespace.
<a href="/details/8675309">Show Account</a>
That would result in:
<link:personList>List People</link:personList>
The link namespace approach allows parameters to be specified as attributes.
<a href="/showPeople">List People</a>
That would result in:
<link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>
To specify attributes that should be applied to the generated href, specify a
<a href="/details/8675309">Show Account</a>
Map value to the
attrs attribute. These attributes will be applied
directly to the href, not passed through to be used as request parameters.
That would result in:
<link:accountDetails attrs="[class: 'fancy']" acctNumber="8675309">Show Account</link:accountDetails>
<a href="/details/8675309" class="fancy">Show Account</a>
6.5 Web Flow
OverviewGrails supports the creation of web flows built on the Spring Web Flow project. A web flow is a conversation that spans multiple requests and retains state for the scope of the flow. A web flow also has a defined start and end state.Web flows don't require an HTTP session, but instead store their state in a serialized form, which is then restored using a flow execution key that Grails passes around as a request parameter. This makes flows far more scalable than other forms of stateful application that use the HttpSession and its inherit memory and clustering concerns.Web flow is essentially an advanced state machine that manages the "flow" of execution from one state to the next. Since the state is managed for you, you don't have to be concerned with ensuring that users enter an action in the middle of some multi step flow, as web flow manages that for you. This makes web flow perfect for use cases such as shopping carts, hotel booking and any application that has multi page work flows.
From Grails 1.2 onwards you must install the Webflow plugin to use this feature:
grails install-plugin webflow
Creating a FlowTo create a flow create a regular Grails controller and then add an action that ends with the convention
Flow. For example:
Notice when redirecting or referring to the flow as an action we omit the
class BookController {
def index = {
def shoppingCartFlow = {
Flow suffix. In other words the name of the action of the above flow is
6.5.1 Start and End StatesAs mentioned before a flow has a defined start and end state. A start state is the state which is entered when a user first initiates a conversation (or flow). The start state of A Grails flow is the first method call that takes a block. For example:
Here the
class BookController { … def shoppingCartFlow = { showCart { on("checkout").to "enterPersonalDetails" on("continueShopping").to "displayCatalogue" } … displayCatalogue { redirect(controller:"catalogue", action:"show") } displayInvoice() } }
showCart node is the start state of the flow. Since the showCart state doesn't define an action or redirect it is assumed be a view state that, by convention, refers to the view
grails-app/views/book/shoppingCart/showCart.gsp.Notice that unlike regular controller actions, the views are stored within a directory that matches the name of the flow:
shoppingCart flow also has two possible end states. The first is
displayCatalogue which performs an external redirect to another controller and action, thus exiting the flow. The second is
displayInvoice which is an end state as it has no events at all and will simply render a view called
grails-app/views/book/shoppingCart/displayInvoice.gsp whilst ending the flow at the same time.Once a flow has ended it can only be resumed from the start state, in this case
showCart, and not from any other state.
6.5.2 Action States and View States
View statesA view state is a one that doesn't define an
action or a
redirect. So for example the below is a view state:
It will look for a view called
enterPersonalDetails { on("submit").to "enterShipping" on("return").to "showCart" }
grails-app/views/book/shoppingCart/enterPersonalDetails.gsp by default. Note that the
enterPersonalDetails state defines two events:
submit and
return. The view is responsible for triggering these events. If you want to change the view to be rendered you can do so with the render method:
Now it will look for
enterPersonalDetails { render(view:"enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }
grails-app/views/book/shoppingCart/enterDetailsView.gsp. If you want to use a shared view, start with a / in view argument:
Now it will look for
enterPersonalDetails { render(view:"/shared/enterDetailsView") on("submit").to "enterShipping" on("return").to "showCart" }
Action StatesAn action state is a state that executes code but does not render any view. The result of the action is used to dictate flow transition. To create an action state you need to define an action to to be executed. This is done by calling the
action method and passing it a block of code to be executed:
As you can see an action looks very similar to a controller action and in fact you can re-use controller actions if you want. If the action successfully returns with no errors the
listBooks { action { [ bookList:Book.list() ] } on("success").to "showCatalogue" on(Exception).to "handleError" }
success event will be triggered. In this case since we return a map, this is regarded as the "model" and is automatically placed in flow scope.
In addition, in the above example we also use an exception handler to deal with errors on the line:
What this does is make the flow transition to a state called
on(Exception).to "handleError"
handleError in the case of an exception.You can write more complex actions that interact with the flow request context:
Here is a more complex action that gathers all the information accumulated from the flow scope and creates an
processPurchaseOrder { action { def a = flow.address def p = flow.person def pd = flow.paymentDetails def cartItems = flow.cartItems flow.clear() def o = new Order(person:p, shippingAddress:a, paymentDetails:pd) o.invoiceNumber = new Random().nextInt(9999999) cartItems.each { o.addToItems(it) } o.save() [order:o] } on("error").to "confirmPurchase" on(Exception).to "confirmPurchase" on("success").to "displayInvoice" }
Order object. It then returns the order as the model. The important thing to note here is the interaction with the request context and "flow scope".
Transition ActionsAnother form of action is what is known as a transition action. A transition action is executed directly prior to state transition once an event has been triggered. A trivial example of a transition action can be seen below:
Notice how we pass a block of the code to
enterPersonalDetails { on("submit") { log.trace "Going to enter shipping" }.to "enterShipping" on("return").to "showCart" }
submit event that simply logs the transition. Transition states are extremely useful for data binding and validation, which is covered in a later section.
6.5.3 Flow Execution EventsIn order to transition execution of a flow from one state to the next you need some way of trigger an event that indicates what the flow should do next. Events can be triggered from either view states or action states.
Triggering Events from a View StateAs discussed previously the start state of the flow in a previous code listing deals with two possible events. A
checkout event and a
continueShopping event:
Since the
def shoppingCartFlow = { showCart { on("checkout").to "enterPersonalDetails" on("continueShopping").to "displayCatalogue" } … }
showCart event is a view state it will render the view
grails-app/book/shoppingCart/showCart.gsp. Within this view you need to have components that trigger flow execution. On a form this can be done use the submitButton tag:
The form must submit back to the
<g:form action="shoppingCart"> <g:submitButton name="continueShopping" value="Continue Shopping"></g:submitButton> <g:submitButton name="checkout" value="Checkout"></g:submitButton> </g:form>
shoppingCart flow. The name attribute of each submitButton tag signals which event will be triggered. If you don't have a form you can also trigger an event with the link tag as follows:
<g:link action="shoppingCart" event="checkout" />
Triggering Events from an ActionTo trigger an event from an
action you need to invoke a method. For example there is the built in
error() and
success() methods. The example below triggers the
error() event on validation failure in a transition action:
In this case because of the error the transition action will make the flow go back to the
enterPersonalDetails { on("submit") { def p = new Person(params) flow.person = p if(!p.validate())return error() }.to "enterShipping" on("return").to "showCart" }
enterPersonalDetails state.With an action state you can also trigger events to redirect flow:
shippingNeeded { action { if(params.shippingRequired) yes() else no() } on("yes").to "enterShipping" on("no").to "enterPayment" }
6.5.4 Flow Scopes
Scope BasicsYou'll notice from previous examples that we used a special object called
flow to store objects within "flow scope". Grails flows have 5 different scopes you can utilize:
request- Stores an object for the scope of the current request
flash- Stores the object for the current and next request only
flow- Stores objects for the scope of the flow, removing them when the flow reaches an end state
conversation- Stores objects for the scope of the conversation including the root flow and nested subflows
session- Stores objects inside the users session
Grails service classes can be automatically scoped to a web flow scope. See the documentation on Services for more information.Also returning a model map from an action will automatically result in the model being placed in flow scope. For example, using a transition action, you can place objects within
flow scope as follows:
Be aware that a new request is always created for each state, so an object placed in request scope in an action state (for example) will not be available in a subsequent view state. Use one of the other scopes to pass objects from one state to another. Also note that Web Flow:
enterPersonalDetails { on("submit") { [person:new Person(params)] }.to "enterShipping" on("return").to "showCart" }
- Moves objects from flash scope to request scope upon transition between states;
- Merges objects from the flow and conversation scopes into the view model before rendering (so you shouldn't include a scope prefix when referencing these objects within a view, e.g. GSP pages).
Flow Scopes and SerializationWhen placing objects in
flow or
conversation scope they must implement
java.io.Serializable otherwise you will get an error. This has an impact on domain classes in that domain classes are typically placed within a scope so that they can be rendered in a view. For example consider the following domain class:
In order to place an instance of the
class Book {
String title
Book class in a flow scope you will need to modify it as follows:
This also impacts associations and closures you declare within a domain class. For example consider this:
class Book implements Serializable { String title }
Here if the
class Book implements Serializable { String title Author author }
Author association is not
Serializable you will also get an error. This also impacts closures used in GORM events such as
onSave and so on. The following domain class will cause an error if an instance is placed in a flow scope:
The reason is that the assigned block on the
class Book implements Serializable { String title def onLoad = { println "I'm loading" } }
onLoad event cannot be serialized. To get around this you should declare all events as
class Book implements Serializable { String title transient onLoad = { println "I'm loading" } }
6.5.5 Data Binding and ValidationIn the section on start and end states, the start state in the first example triggered a transition to the
enterPersonalDetails state. This state renders a view and waits for the user to enter the required information:
The view contains a form with two submit buttons that either trigger the submit event or the return event:
enterPersonalDetails { on("submit").to "enterShipping" on("return").to "showCart" }
However, what about the capturing the information submitted by the form? To to capture the form info we can use a flow transition action:
<g:form action="shoppingCart"> <!-- Other fields --> <g:submitButton name="submit" value="Continue"></g:submitButton> <g:submitButton name="return" value="Back"></g:submitButton> </g:form>
Notice how we perform data binding from request parameters and place the
enterPersonalDetails { on("submit") { flow.person = new Person(params) !flow.person.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }
Person instance within
flow scope. Also interesting is that we perform validation and invoke the
error() method if validation fails. This signals to the flow that the transition should halt and return to the
enterPersonalDetails view so valid entries can be entered by the user, otherwise the transition should continue and go to the
enterShipping state.Like regular actions, flow actions also support the notion of Command Objects by defining the first argument of the closure:
enterPersonalDetails { on("submit") { PersonDetailsCommand cmd -> flow.personDetails = cmd !flow.personDetails.validate() ? error() : success() }.to "enterShipping" on("return").to "showCart" }
6.5.6 Subflows and ConversationsGrails' Web Flow integration also supports subflows. A subflow is like a flow within a flow. For example take this search flow:
It references a subflow in the
def searchFlow = { displaySearchForm { on("submit").to "executeSearch" } executeSearch { action { [results:searchService.executeSearch(params.q)] } on("success").to "displayResults" on("error").to "displaySearchForm" } displayResults { on("searchDeeper").to "extendedSearch" on("searchAgain").to "displaySearchForm" } extendedSearch { subflow(controller: "searchExtensions", action: "extendedSearch") // <--- extended search subflow on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" } displayMoreResults() displayNoMoreResults() }
extendedSearch state. The controller parameter is optional if the subflow is defined in the same controller as the calling flow.
Prior to 1.3.5, the previous subflow call would look likeThe subflow is another flow entirely:
subflow(extendedSearchFlow), with the requirement that the name of the subflow state was the same as the called subflow (minus
Flow). This way of calling a subflow is deprecated and only supported for backward compatibility.
Notice how it places the
def extendedSearchFlow = { startExtendedSearch { on("findMore").to "searchMore" on("searchAgain").to "noResults" } searchMore { action { def results = searchService.deepSearch(ctx.conversation.query) if(!results)return error() conversation.extendedResults = results } on("success").to "moreResults" on("error").to "noResults" } moreResults() noResults() }
extendedResults in conversation scope. This scope differs to flow scope as it allows you to share state that spans the whole conversation not just the flow. Also notice that the end state (either
moreResults or
noResults of the subflow triggers the events in the main flow:
extendedSearch { subflow(controller: "searchExtensions", action: "extendedSearch") // <--- extended search subflow on("moreResults").to "displayMoreResults" on("noResults").to "displayNoMoreResults" }
6.6 FiltersAlthough Grails controllers support fine grained interceptors, these are only really useful when applied to a few controllers and become difficult to manage with larger applications. Filters on the other hand can be applied across a whole group of controllers, a URI space or a to a specific action. Filters are far easier to plug-in and maintain completely separately to your main controller logic and are useful for all sorts of cross cutting concerns such as security, logging, and so on.
6.6.1 Applying FiltersTo create a filter create a class that ends with the convention
Filters in the
grails-app/conf directory. Within this class define a code block called
filters that contains the filter definitions:
Each filter you define within the
class ExampleFilters { def filters = { // your filters here } }
filters block has a name and a scope. The name is the method name and the scope is defined using named arguments. For example if you need to define a filter that applies to all controllers and all actions you can use wildcards:
The scope of the filter can be one of the following things:
sampleFilter(controller:'*', action:'*') { // interceptor definitions }
- A controller and/or action name pairing with optional wildcards
- A URI, with Ant path matching syntax
controller- controller matching pattern, by default * is replaced with .* and a regex is compiled
action- action matching pattern, by default * is replaced with .* and a regex is compiled
regex(true/false) - use regex syntax (don't replace '*' with '.*')
uri- a uri to match, expressed with as Ant style path (e.g. /book/**)
find(true/false) - rule matches with partial match (see java.util.regex.Matcher.find())
invert(true/false) - invert the rule (NOT rule)
- All controllers and actions
all(controller:'*', action:'*') {}
- Only for the
justBook(controller:'book', action:'*') {}
- All controllers except the
notBook(controller:'book', invert:true) {}
- All actions containing 'save' in the action name
saveInActionName(action:'save', find:true) {}
- Applied to a URI space
someURIs(uri:'/book/**') {}
- Applied to all URIs
In addition, the order in which you define the filters within the
allURIs(uri:'/**') {}
filters code block dictates the order in which they are executed. To control the order of execution between
Filters classes, you can use the
dependsOn property discussed in filter dependencies section.
6.6.2 Filter TypesWithin the body of the filter you can then define one or several of the following interceptor types for the filter:
before- Executed before the action. Can return false to indicate all future filters and the action should not execute
after- Executed after an action. Takes a first argument as the view model
afterView- Executed after view rendering. Takes an Exception as an argument. Note: this closure is called before the layout is applied.
Here the
class SecurityFilters { def filters = { loginCheck(controller:'*', action:'*') { before = { if(!session.user && !actionName.equals('login')) { redirect(action:'login') return false } } } } }
loginCheck filter uses a
before interceptor to execute a block of code that checks if a user is in the session and if not redirects to the login action. Note how returning false ensure that the action itself is not executed.
6.6.3 Variables and ScopesFilters support all the common properties available to controllers and tag libraries, plus the application context:
- request - The HttpServletRequest object
- response - The HttpServletResponse object
- session - The HttpSession object
- servletContext - The ServletContext object
- flash - The flash object
- params - The request parameters object
- actionName - The action name that is being dispatched to
- controllerName - The controller name that is being dispatched to
- grailsApplication - The Grails application currently running
- applicationContext - The ApplicationContext object
6.6.4 Filter DependenciesIn a
Filters class, you can specify any other
Filters classes that should first be executed using the
dependsOn property. The
dependsOn property is used when a
Filters class depends on the behavior of another
Filters class (e.g. setting up the environment, modifying the request/session, etc.) and is defined as an array of
Filters classes.Take the following example
Filters classes:
MyFilters specifically
class MyFilters { def dependsOn = [MyOtherFilters] def filters = { checkAwesome(uri:"/*") { before = { if (request.isAwesome) { // do something awesome } } } checkAwesome2(uri:"/*") { before = { if (request.isAwesome) { // do something else awesome } } } } }class MyOtherFilters { def filters = { makeAwesome(uri:"/*") { before = { request.isAwesome = true; } } doNothing(uri:"/*") { before = { // do nothing } } } }
dependsOn MyOtherFilters. This will cause all the filters in MyOtherFilters to be executed before those in MyFilters, given their scope matches the current request. For a request of "/test", which will match the scope of every filter in the example, the execution order would be as follows:
- MyOtherFilters - makeAwesome
- MyOtherFilters - doNothing
- MyFilters - checkAwesome
- MyFilters - checkAwesome2
Filters classes are enabled and the execution order of filters within each
Filters class are preserved.If any cyclical dependencies are detected, the filters with cyclical dependencies will be added to the end of the filter chain and processing will continue. Information about any cyclical dependencies that are detected will be written to the logs. Ensure that your root logging level is set to at least WARN or configure an appender for the Grails Filters Plugin (org.codehaus.groovy.grails.plugins.web.filters.FiltersGrailsPlugin) when debugging filter dependency issues.
6.7 AjaxAjax stands for Asynchronous Javascript and XML and is the driving force behind the shift to richer web applications. These types of applications in general are better suited to agile, dynamic frameworks written in languages like Ruby and Groovy Grails provides support for building Ajax applications through its Ajax tag library for a full list of these see the Tag Library Reference.
6.7.1 Ajax using PrototypeBy default Grails ships with the Prototype library, but through the Plug-in system provides support for other frameworks such as Dojo Yahoo UI and the Google Web ToolkitThis section covers Grails' support for Prototype. To get started you need to add this line to the
<head> tag of your page:
<g:javascript library="prototype" />
This works because of Grails' support for adaptive tag libraries. Thanks to Grails' plugin system there is support for a number of different Ajax libraries including (but not limited to):
<g:javascript library="scriptaculous" />
- prototype
- dojo
- yui
- mootools
188.8.131.52 Remoting LinkingRemote content can be loaded in a number of ways, the most commons way is through the remoteLink tag. This tag allows the creation of HTML anchor tags that perform an asynchronous request and optionally set the response in an element. The simplest way to create a remote link is as follows:
The above link sends an asynchronous request to the
<g:remoteLink action="delete" id="1">Delete Book</g:remoteLink>
delete action of the current controller with an id of
22.214.171.124 Updating ContentThis is great, but usually you would want to provide some kind of feedback to the user as to what has happened:
GSP code:
def delete = {
def b = Book.get( params.id )
render "Book ${b.id} was deleted"
The above example will call the action and set the contents of the
<div id="message"></div> <g:remoteLink action="delete" id="1" update="message">Delete Book</g:remoteLink>
div to the response in this case
"Book 1 was deleted". This is done by the
update attribute on the tag, which can also take a map to indicate what should be updated on failure:
Here the
<div id="message"></div> <div id="error"></div> <g:remoteLink action="delete" id="1" update="[success:'message',failure:'error']">Delete Book</g:remoteLink>
error div will be updated if the request failed.
126.96.36.199 Remote Form SubmissionAn HTML form can also be submitted asynchronously in one of two ways. Firstly using the formRemote tag which expects similar attributes to those for the remoteLink tag:
Or alternatively you can use the submitToRemote tag to create a submit button. This allows some buttons to submit remotely and some not depending on the action:
<g:formRemote url="[controller:'book',action:'delete']" update="[success:'message',failure:'error']"> <input type="hidden" name="id" value="1" /> <input type="submit" value="Delete Book!" /> </g:formRemote >
<form action="delete"> <input type="hidden" name="id" value="1" /> <g:submitToRemote action="delete" update="[success:'message',failure:'error']" /> </form>
126.96.36.199 Ajax EventsSpecific javascript can be called if certain events occur, all the events start with the "on" prefix and allow you to give feedback to the user where appropriate, or take other action:
The above code will execute the "showProgress()" function which may show a progress bar or whatever is appropriate. Other events include:
<g:remoteLink action="show" id="1" update="success" onLoading="showProgress()" onComplete="hideProgress()">Show Book 1</g:remoteLink>
onSuccess- The javascript function to call if successful
onFailure- The javascript function to call if the call failed
on_ERROR_CODE- The javascript function to call to handle specified error codes (eg on404="alert('not found!')")
onUninitialized- The javascript function to call the a ajax engine failed to initialise
onLoading- The javascript function to call when the remote function is loading the response
onLoaded- The javascript function to call when the remote function is completed loading the response
onComplete- The javascript function to call when the remote function is complete, including any updates
XmlHttpRequest object you can use the implicit event parameter
e to obtain it:
<g:javascript> function fireMe(e) { alert("XmlHttpRequest = " + e) } } </g:javascript> <g:remoteLink action="example" update="success" onSuccess="fireMe(e)">Ajax Link</g:remoteLink>
6.7.2 Ajax with DojoGrails features an external plug-in to add Dojo support to Grails. To install the plug-in type the following command from the root of your project in a terminal window:
This will download the current supported version of Dojo and install it into your Grails project. With that done you can add the following reference to the top of your page:
grails install-plugin dojo
Now all of Grails tags such as remoteLink, formRemote and submitToRemote work with Dojo remoting.
<g:javascript library="dojo" />
6.7.3 Ajax with GWTGrails also features support for the Google Web Toolkit through a plug-in comprehensive documentation for can be found on the Grails wiki.
6.7.4 Ajax on the ServerAlthough Ajax features the X for XML there are a number of different ways to implement Ajax which are typically broken down into:
- Content Centric Ajax - Where you merely use the HTML result of a remote call to update the page
- Data Centric Ajax - Where you actually send an XML or JSON response from the server and programmatically update the page
- Script Centric Ajax - Where the server sends down a stream of Javascript to be evaluated on the fly
Content Centric AjaxJust to re-cap, content centric Ajax involves sending some HTML back from the server and is typically done by rendering a template with the render method:
Calling this on the client involves using the remoteLink tag:
def showBook = {
def b = Book.get(params.id) render(template:"bookTemplate", model:[book:b])
<g:remoteLink action="showBook" id="${book.id}" update="book${book.id}">Update Book</g:remoteLink><div id="book${book.id}"> <!--existing book mark-up --> </div>
Data Centric Ajax with JSONData Centric Ajax typically involves evaluating the response on the client and updating programmatically. For a JSON response with Grails you would typically use Grails' JSON marshaling capability:
And then on the client parse the incoming JSON request using an Ajax event handler:
import grails.converters.*def showBook = {
def b = Book.get(params.id) render b as JSON
<g:javascript> function updateBook(e) { var book = eval("("+e.responseText+")") // evaluate the JSON $("book" + book.id + "_title").innerHTML = book.title } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)">Update Book</g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>
Data Centric Ajax with XMLOn the server side using XML is equally trivial:
However, since DOM is involved the client gets more complicated:
import grails.converters.*def showBook = {
def b = Book.get(params.id) render b as XML
<g:javascript> function updateBook(e) { var xml = e.responseXML var id = xml.getElementsByTagName("book").getAttribute("id") $("book" + id + "_title") = xml.getElementsByTagName("title")[0].textContent } <g:javascript> <g:remoteLink action="test" update="foo" onSuccess="updateBook(e)">Update Book</g:remoteLink> <g:set var="bookId">book${book.id}</g:set> <div id="${bookId}"> <div id="${bookId}_title">The Stand</div> </div>
Script Centric Ajax with JavaScriptScript centric Ajax involves actually sending Javascript back that gets evaluated on the client. An example of this can be seen below:
The important thing to remember is to set the
def showBook = { def b = Book.get(params.id) response.contentType = "text/javascript" String title = b.title.encodeAsJavascript() render "$('book${b.id}_title')='${title}'" }
contentType to
text/javascript. If you are using Prototype on the client the returned Javascript will automatically be evaluated due to this
contentType setting.Obviously in this case it is critical that you have an agreed client-side API as you don't want changes on the client breaking the server. This is one of the reasons Rails has something like RJS. Although Grails does not currently have a feature such as RJS there is a Dynamic JavaScript Plug-in that offers similar capabilities.
6.8 Content NegotiationGrails has built in support for Content negotiation using either the HTTP
Accept header, an explicit format request parameter or the extension of a mapped URI.
Configuring Mime TypesBefore you can start dealing with content negotiation you need to tell Grails what content types you wish to support. By default Grails comes configured with a number of different content types within
grails-app/conf/Config.groovy using the
grails.mime.types setting:
The above bit of configuration allows Grails to detect to format of a request containing either the 'text/xml' or 'application/xml' media types as simply 'xml'. You can add your own types by simply adding new entries into the map.
grails.mime.types = [ xml: ['text/xml', 'application/xml'], text: 'text-plain', js: 'text/javascript', rss: 'application/rss+xml', atom: 'application/atom+xml', css: 'text/css', csv: 'text/csv', all: '*/*', json: 'text/json', html: ['text/html','application/xhtml+xml'] ]
Content Negotiation using the Accept headerEvery incoming HTTP request has a special Accept header that defines what media types (or mime types) a client can "accept". In older browsers this is typically:
Which simply means anything. However, on newer browser something all together more useful is sent such as (an example of a Firefox
Accept header):
Grails parses this incoming format and adds a
property to the request object that outlines the preferred request format. For the above example the following assertion would pass:
Why? The
assert 'html' == request.format
text/html media type has the highest "quality" rating of 0.9, therefore is the highest priority. If you have an older browser as mentioned previously the result is slightly different:
In this case 'all' possible formats are accepted by the client. To deal with different kinds of requests from Controllers you can use the withFormat method that acts as kind of a switch statement:
assert 'all' == request.format
What happens here is that if the preferred format is
import grails.converters.*class BookController { def books def list = { this.books = Book.list() withFormat { html bookList:books js { render "alert('hello')" } xml { render books as XML } } } }
html then Grails will execute the
html() call only. What this is does is make Grails look for a view called either
grails-app/views/books/list.html.gsp or
grails-app/views/books/list.gsp. If the format is
xml then the closure will be invoked and an XML response rendered.How do we handle the "all" format? Simply order the content-types within your
withFormat block so that whichever one you want executed comes first. So in the above example, "all" will trigger the
html handler.
When using withFormat make sure it is the last call in your controller action as the return value of the
withFormat method is used by the action to dictate what happens next.
Content Negotiation with the format Request ParameterIf fiddling with request headers if not your favorite activity you can override the format used by specifying a
format request parameter:
You can also define this parameter in the URL Mappings definition:
"/book/list"(controller:"book", action:"list") { format = "xml" }
Content Negotiation with URI ExtensionsGrails also supports content negotiation via URI extensions. For example given the following URI:
Grails will shave off the extension and map it to
/book/list instead whilst simultaneously setting the content format to
xml based on this extension. This behaviour is enabled by default, so if you wish to turn it off, you must set the
grails.mime.file.extensions property in
grails-app/conf/Config.groovy to
grails.mime.file.extensions = false
Testing Content NegotiationTo test content negotiation in an integration test (see the section on Testing) you can either manipulate the incoming request headers:
Or you can set the format parameter to achieve a similar effect:
void testJavascriptOutput() { def controller = new TestController() controller.request.addHeader "Accept", "text/javascript, text/html, application/xml, text/xml, */*" controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }
void testJavascriptOutput() { def controller = new TestController() controller.params.format = 'js' controller.testAction() assertEquals "alert('hello')", controller.response.contentAsString }
7. ValidationGrails validation capability is built on Spring's Validator API and data binding capabilities. However Grails takes this further and provides a unified way to define validation "constraints" with its constraints mechanism.Constraints in Grails are a way to declaratively specify validation rules. Most commonly they are applied to domain classes, however URL Mappings and Command Objects also support constraints.
7.1 Declaring ConstraintsWithin a domain class a constraints are defined with the constraints property that is assigned a code block:
You then use method calls that match the property name for which the constraint applies in combination with named parameters to specify constraints:
class User { String login String password String email Integer age static constraints = { … } }
In this example we've declared that the
class User { ... static constraints = { login(size:5..15, blank:false, unique:true) password(size:5..15, blank:false) email(email:true, blank:false) age(min:18, nullable:false) } }
login property must be between 5 and 15 characters long, it cannot be blank and must be unique. We've all applied other constraints to the
email and
age properties.A complete reference for the available constraints can be found in the left navigation bar (if you have frames enabled) under the Constraints heading.
A word of warning - referencing domain class properties from constraintsIt's very easy to reference instance variables from the static constraints block, but this isn't legal in Groovy (or Java). If you do so, you will get a
MissingPropertyException for your trouble. For example, you may try
See how the
class Response { Survey survey Answer answer static constraints = { survey blank: false answer blank: false, inList: survey.answers } }
inList constraint references the instance property
survey? That won't work. Instead, use a custom validator:
In this example, the
class Response { … static constraints = { survey blank: false answer blank: false, validator: { val, obj -> val in obj.survey.answers } } }
obj argument to the custom validator is the domain instance that is being validated, so we can access its
survey property and return a boolean to indicate whether the new value for the
answer property,
val, is valid or not.
7.2 Validating Constraints
Validation BasicsTo validate a domain class you can call the validate method on any instance:
def user = new User(params)if(user.validate()) { // do something with user } else { user.errors.allErrors.each { println it } }
errors property on domain classes is an instance of the Spring Errors interface. The
Errors interface provides methods to navigate the validation errors and also retrieve the original values.
Validation PhasesWithin Grails there are essentially 2 phases of validation, the first phase is data binding which occurs when you bind request parameters onto an instance such as:
At this point you may already have errors in the
def user = new User(params)
errors property due to type conversion (such as converting Strings to Dates). You can check these and obtain the original input value using the
Errors API:
The second phase of validation happens when you call validate or save. This is when Grails will validate the bound values againts the constraints you defined. For example, by default the persistent save method calls
if(user.hasErrors()) { if(user.errors.hasFieldErrors("login")) { println user.errors.getFieldError("login").rejectedValue } }
validate before executing hence allowing you to write code like:
if(user.save()) { return user } else { user.errors.allErrors.each { println it } }
7.3 Validation on the Client
Displaying ErrorsTypically if you get a validation error you want to redirect back to the view for rendering. Once there you need some way of rendering errors. Grails supports a rich set of tags for dealing with errors. If you simply want to render the errors as a list you can use renderErrors:
If you need more control you can use hasErrors and eachError:
<g:renderErrors bean="${user}" />
<g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li>${err}</li> </g:eachError> </ul> </g:hasErrors>
Highlighting ErrorsIt is often useful to highlight using a red box or some indicator when a field has been incorrectly input. This can also be done with the hasErrors by invoking it as a method. For example:
What this code does is check if the
<div class='value ${hasErrors(bean:user,field:'login','errors')}'> <input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/> </div>
login field of the
user bean has any errors and if it does adds an
errors CSS class to the
div thus allowing you to use CSS rules to highlight the
Retrieving Input ValuesEach error is actually an instance of the FieldError class in Spring, which retains the original input value within it. This is useful as you can use the error object to restore the value input by the user using the fieldValue tag:
This code will look if there is an existing
<input type="text" name="login" value="${fieldValue(bean:user,field:'login')}"/>
FieldError in the
User bean and if there is obtain the originally input value for the
login field.
7.4 Validation and InternationalizationAnother important thing to note about errors in Grails is that the messages that the errors display are not hard coded anywhere. The FieldError class in Spring essentially resolves messages from message bundles using Grails' i18n support.
Constraints and Message CodesThe codes themselves are dictated by a convention. For example consider the constraints we looked at earlier:
If the
package com.mycompany.myappclass User { ... static constraints = { login(size:5..15, blank:false, unique:true) password(size:5..15, blank:false) email(email:true, blank:false) age(min:18, nullable:false) } }
blank constraint was violated Grails will, by convention, look for a message code in the form:
In the case of the
[Class Name].[Property Name].[Constraint Code]
blank constraint this would be
user.login.blank so you would need a message such as the following in your
grails-app/i18n/messages.properties file:
The class name is looked for both with and without a package, with the packaged version taking precedence. So for example, com.mycompany.myapp.User.login.blank will be used before user.login.blank. This allows for cases where you domain class encounters message code clashes with plugins.For a reference on what codes are for which constraints refer to the reference guide for each constraint.
user.login.blank=Your login name must be specified!
Displaying MessagesThe renderErrors tag will automatically deal with looking up messages for you using the message tag. However, if you need more control of rendering you will need to do this yourself:
In this example within the body of the eachError tag we use the message tag in combination with its
<g:hasErrors bean="${user}"> <ul> <g:eachError var="err" bean="${user}"> <li><g:message error="${err}" /></li> </g:eachError> </ul> </g:hasErrors>
error argument to read the message for the given error.
7.5 Validation Non Domain and Command Object ClassesDomain classes and command objects support validation by default. Other classes may be made validateable by defining the static constraints property in the class (as described above) and then telling the framework about them. It is important that the application register the validateable classes with the framework. Simply defining the constraints property is not sufficient.
The Validateable AnnotationClasses which define the static constraints property and are marked with the @Validateable annotation may be made validateable by the framework. Consider this example:
You need to tell the framework which packages to search for @Validateable classes by assigning a list of Strings to the grails.validateable.packages property in Config.groovy.
// src/groovy/com/mycompany/myapp/User.groovy package com.mycompany.myappimport org.codehaus.groovy.grails.validation.Validateable@Validateable class User { ... static constraints = { login(size:5..15, blank:false, unique:true) password(size:5..15, blank:false) email(email:true, blank:false) age(min:18, nullable:false) } }
The framework will only search those packages (and child packages of those) for classes marked with @Validateable.
// grails-app/conf/Config.groovy...grails.validateable.packages = ['com.mycompany.dto', 'com.mycompany.util']...
Registering Validateable ClassesIf a class is not marked with @Validateable, it may still be made validateable by the framework. The steps required to do this are to define the static constraints property in the class (as described above) and then telling the framework about the class by assigning a value to the grails.validateable.classes property in Config.groovy.
// grails-app/conf/Config.groovy...grails.validateable.classes = [com.mycompany.myapp.User, com.mycompany.dto.Account]...
8. The Service LayerAs well as the Web layer, Grails defines the notion of a service layer. The Grails team discourages the embedding of core application logic inside controllers, as it does not promote re-use and a clean separation of concerns.Services in Grails are seen as the place to put the majority of the logic in your application, leaving controllers responsible for handling request flow via redirects and so on.
Creating a ServiceYou can create a Grails service by running the create-service command from the root of your project in a terminal window:
The above example will create a service at the location
grails create-service simple
grails-app/services/SimpleService.groovy. A service's name ends with the convention
Service, other than that a service is a plain Groovy class:
class SimpleService { }
8.1 Declarative Transactions
Default Declarative TransactionsServices are typically involved with co-ordinating logic between domain classes, and hence often involved with persistence that spans large operations. Given the nature of services they frequently require transactional behaviour. You can of course use programmatic transactions with the withTransaction method, however this is repetitive and doesn't fully leverage the power of Spring's underlying transaction abstraction.Services allow the enablement of transaction demarcation, which is essentially a declarative way of saying all methods within this service are to be made transactional. All services have transaction demarcation enabled by default - to disable it, simply set the
transactional property to
You may also set this property to
class CountryService { static transactional = false }
true in case the default changes in the future, or simply to make it clear that the service is intentionally transactional.
Warning: dependency injection is the only way that declarative transactions work. You will not get a transactional service if you use theThe result is all methods are wrapped in a transaction and automatic rollback occurs if an exception is thrown in the body of one of the methods. The propagation level of the transaction is by default set to PROPAGATION_REQUIRED.
newoperator such as
new BookService()
Custom Transaction ConfigurationGrails also fully supports Spring's
Transactional annotation for cases where you need more fine-grained control over transactions at a per-method level or need specify an alternative propagation level:
For more information refer to the section of the Spring user guide on Using @Transactional.
import org.springframework.transaction.annotation.*class BookService { @Transactional(readOnly = true) def listBooks() { Book.list() } @Transactional def updateBook() { // … }}
Unlike Spring you do not need any prior configuration to use
Transactional, just specify the annotation as needed and Grails will pick them up automatically.
8.2 Scoped ServicesBy default, access to service methods is not synchronised, so nothing prevents concurrent execution of those functions. In fact, because the service is a singleton and may be used concurrently, you should be very careful about storing state in a service. Or take the easy (and better) road and never store state in a service.You can change this behaviour by placing a service in a particular scope. The supported scopes are:
prototype- A new service is created every time it is injected into another class
request- A new service will be created per request
flash- A new service will be created for the current and next request only
flow- In web flows the service will exist for the scope of the flow
conversation- In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows
session- A service is created for the scope of a user session
singleton(default) - Only one instance of the service ever exists
If your service isTo enable one of the scopes, add a static scope property to your class whose value is one of the above:
conversationscoped it will need to implement
java.io.Serializableand can only be used in the context of a Web Flow
static scope = "flow"
8.3 Dependency Injection and Services
Dependency Injection BasicsA key aspect of Grails services is the ability to take advantage of the Spring Framework's dependency injection capability. Grails supports "dependency injection by convention". In other words, you can use the property name representation of the class name of a service, to automatically inject them into controllers, tag libraries, and so on.As an example, given a service called
BookService, if you place a property called
bookService within a controller as follows:
In this case, the Spring container will automatically inject an instance of that service based on its configured scope. All dependency injection is done by name. You can also specify the type as follows:
class BookController { def bookService … }
class AuthorService { BookService bookService }
NOTE: Normally the property name is generated by lower casing the first letter of the type. For example, an instance of the
BookServiceclass would map to a property named
bookService.To be consistent with standard JavaBean convetions, if the first 2 letters of the class name are upper case, the property name is the same as the class name. For example, an instance of the
MYhelperServiceclass would map to a property named
MYhelperService.See section 8.8 of the JavaBean specification for more information on de-capitalization rules.
Dependency Injection and ServicesYou can inject services in other services with the same technique. Say you had an
AuthorService that needed to use the
BookService, declaring the
AuthorService as follows would allow that:
class AuthorService { def bookService }
Dependency Injection and Domain ClassesYou can even inject services into domain classes, which can aid in the development of rich domain models:
class Book {
def bookService
def buyBook() {
8.4 Using Services from JavaOne of the powerful things about services is that since they encapsulate re-usable logic, you can use them from other classes, including Java classes. There are a couple of ways you can re-use a service from Java. The simplest way is to move your service into a package within the
grails-app/services directory. The reason this is a critical step is that it is not possible to import classes into Java from the default package (the package used when no package declaration is present). So for example the
BookService below cannot be used from Java as it stands:
However, this can be rectified by placing this class in a package, by moving the class into a sub directory such as
class BookService { void buyBook(Book book) { // logic } }
grails-app/services/bookstore and then modifying the package declaration:
An alternative to packages is to instead have an interface within a package that the service implements:
package bookstore
class BookService {
void buyBook(Book book) {
// logic
And then the service:
package bookstore; interface BookStore { void buyBook(Book book); }
This latter technique is arguably cleaner, as the Java side only has a reference to the interface and not to the implementation class. Either way, the goal of this exercise to enable Java to statically resolve the class (or interface) to use, at compile time. Now that this is done you can create a Java class within the
class BookService implements bookstore.BookStore {
void buyBook(Book b) {
// logic
src/java package, and provide a setter that uses the type and the name of the bean in Spring:
Once this is done you can configure the Java class as a Spring bean in
package bookstore; // note: this is Java class public class BookConsumer { private BookStore store; public void setBookStore(BookStore storeInstance) { this.store = storeInstance; } … }
grails-app/conf/spring/resources.xml (For more information one this see the section on Grails and Spring):
<bean id="bookConsumer" class="bookstore.BookConsumer"> <property name="bookStore" ref="bookService" /> </bean>
9. TestingAutomated testing is seen as a key part of Grails, implemented using Groovy Tests. Hence, Grails provides many ways to making testing easier from low level unit testing to high level functional tests. This section details the different capabilities that Grails offers in terms of testing.The first thing to be aware of is that all of the
create-* commands actually end up creating
unit tests automatically for you. For example say you run the create-controller command as follows:
Not only will Grails create a controller at
grails create-controller com.yourcompany.yourapp.simple
grails-app/controllers/com/yourcompany/yourapp/SimpleController.groovy, but also an unit test at
test/unit/com/yourcompany/yourapp/SimpleControllerTests.groovy. What Grails won't do however is populate the logic inside the test! That is left up to you.
As of Grails 1.2.2,the suffix of
Test is also supported for test cases.
Running TestsTest are run with the test-app command:
The above command will produce output such as:
grails test-app
Whilst reports will have been written out the
------------------------------------------------------- Running Unit Tests… Running test FooTests...FAILURE Unit Tests Completed in 464ms … -------------------------------------------------------Tests failed: 0 errors, 1 failures
target/test-reports directory.
You can force a clean before running tests by passing
-cleanto the
Targeting TestsYou can selectively target the test(s) to be run in different ways. To run all tests for a controller named
SimpleController you would run:
This will run any tests for the class named
grails test-app SimpleController
SimpleController. Wildcards can be used...
This will test all classes ending in
grails test-app *Controller
Controller. Package names can optionally be specified...
or to run all tests in a package...
grails test-app some.org.*Controller
or to run all tests in a package including subpackages...
grails test-app some.org.*
You can also target particular test methods...
grails test-app some.org.**
This will run the
grails test-app SimpleController.testLogin
testLogin test in the
SimpleController tests. You can specify as many patterns in combination as you like...
grails test-app some.org.* SimpleController.testLogin BookController
Targeting Test Types and/or PhasesIn addition to targeting certain tests, you can also target test types and/or phases by using the
phase:type syntax.
Grails organises tests by phase and by type. A test phase relates to the state of the Grails application during the tests, and the type relates to the testing mechanism.Grails comes with support for 4 test phases (To execute the JUnit
other) and JUnit test types for the
integrationphases. These test types have the same name as the phase.Testing plugins may provide new test phases or new test types for existing phases. Refer to the plugin documentation.
integration tests you can run:
grails test-app integration:integration
phase and
type are optional. Their absence acts as a wildcard. The following command will run all test types in the
unit phase:
The Grails Spock Plugin is one plugin that adds new test types to Grails. It adds a
grails test-app unit:
spock test type to the
integration and
functional phases. To run all spock tests in all phases you would run the following:
To run the all of the spock tests in the
grails test-app :spock
functional phase you would run...
More than one pattern can be specified...
grails test-app functional:spock
grails test-app unit:spock integration:spock
Targeting Tests in Types and/or PhasesTest and type/phase targetting can be applied at the same time:
This would run all tests in the
grails test-app integration: unit: some.org.**
integration and
unit phases that are in the page
some.org or a subpackage of.
9.1 Unit TestingUnit testing are tests at the "unit" level. In other words you are testing individual methods or blocks of code without considering for surrounding infrastructure. In Grails you need to be particularity aware of the difference between unit and integration tests because in unit tests Grails does not inject any of the dynamic methods present during integration tests and at runtime.This makes sense if you consider that the methods injected by Grails typically communicate with the database (with GORM) or the underlying Servlet engine (with Controllers). For example say you have service like the following in
As you can see the service takes advantage of GORM methods. So how do you go about testing the above code in a unit test? The answer can be found in Grails' testing support classes.
class MyService { def otherService String createSomething() { def stringId = otherService.newIdentifier() def item = new Item(code: stringId, name: "Bangle") item.save() return stringId } int countItems(String name) { def items = Item.findAllByName(name) return items.size() } }
The Testing FrameworkThe core of the testing plugin is the
grails.test.GrailsUnitTestCase class. This is a sub-class of
GroovyTestCase geared towards Grails applications and their artifacts. It provides several methods for mocking particular types as well as support for general mocking a la Groovy's MockFor and StubFor classes.Normally you might look at the
MyService example shown previously and the dependency on another service and the use of dynamic domain class methods with a bit of a groan. You can use meta-class programming and the "map as object" idiom, but these can quickly get ugly. How might we write the test with GrailsUnitTestCase ?
OK, so a fair bit of new stuff there, but once we break it down you should quickly see how easy it is to use the methods available to you. Take a look at the "testCreateSomething()" test method. The first thing you will probably notice is the
import grails.test.GrailsUnitTestCaseclass MyServiceTests extends GrailsUnitTestCase { void testCreateSomething() { // Mock the domain class. mockDomain(Item) // Mock the "other" service. String testId = "NH-12347686" def otherControl = mockFor(OtherService) otherControl.demand.newIdentifier(1..1) {-> return testId } // Initialise the service and test the target method. def testService = new MyService() testService.otherService = otherControl.createMock() def retval = testService.createSomething() // Check that the method returns the identifier returned by the // mock "other" service and also that a new Item instance has // been saved. def testInstances = Item.list() assertEquals testId, retval assertEquals 1, testInstances.size() assertTrue testInstances[0] instanceof Item } void testCountItems() { // Mock the domain class, this time providing a list of test // Item instances that can be searched. def testInstances = [ new Item(code: "NH-4273997", name: "Laptop"), new Item(code: "EC-4395734", name: "Lamp"), new Item(code: "TF-4927324", name: "Laptop") ] mockDomain(Item, testInstances) // Initialise the service and test the target method. def testService = new MyService() assertEquals 2, testService.countItems("Laptop") assertEquals 1, testService.countItems("Lamp") assertEquals 0, testService.countItems("Chair") } }
mockDomain() method, which is one of several provided by
It adds all the common domain methods (both instance and static) to the given class so that any code using it sees it as a full-blown domain class. So for example, once the
def testInstances = [] mockDomain(Item, testInstances)
Item class has been mocked, we can safely call the
save() method on instances of it. Invoking the
save() method doesn't really save the instance to any database but it will cache the object in the testing framework so the instance will be visible to certain queries. The following code snippet demonstrates the effect of calling the
save() method.
The next bit we want to look at is centered on the
void testSomething() { def testInstances=[] mockDomain(Song, testInstances) assertEquals(0, Song.count()) new Song(name:"Supper's Ready").save() assertEquals(1, Song.count()) }
mockFor method:
This is analagous to the
def otherControl = mockFor(OtherService)
otherControl.demand.newIdentifier(1..1) {-> return testId }
MockFor and
StubFor classes that come with Groovy and it can be used to mock any class you want. In fact, the "demand" syntax is identical to that used by Mock/StubFor, so you should feel right at home. Of course you often need to inject a mock instance as a dependency, but that is pretty straight forward with the
createMock() method, which you simply call on the mock control as shown. For those familiar with EasyMock, the name
otherControl highlights the role of the object returned by
mockFor() - it is a control object rather than the mock itself.The rest of the
testCreateSomething() method should be pretty familiar, particularly as you now know that the mock
save() method adds instances to
testInstances list. However, there is an important technique missing from the test method. We can determine that the mock
newIdentifier() method is called because its return value has a direct impact on the result of the
createSomething() method. But what if that weren't the case? How would we know whether it had been called or not? With Mock/StubFor the check would be performed at the end of the
use() closure, but that's not available here. Instead, you can call
verify() on the control object - in this case
otherControl. This will perform the check and throw an assertion error if it hasn't been called when it should have been.Lastly,
testCountItems() in the example demonstrates another facet of the
mockDomain() method:
It is normally quite fiddly to mock the dynamic finders manually, and you often have to set up different data sets for each invocation. On top of that, if you decide a different finder should be used then you have to update the tests to check for the new method! Thankfully the
def testInstances = [ new Item(code: "NH-4273997", name: "Laptop"), new Item(code: "EC-4395734", name: "Lamp"), new Item(code: "TF-4927324", name: "Laptop") ] mockDomain(Item, testInstances)
mockDomain() method provides a lightweight implementation of the dynamic finders backed by a list of domain instances. Simply provide the test data as the second argument of the method and the mock finders will just work.
GrailsUnitTestCase - the mock methodsYou have already seen a couple of examples in the introduction of the
mock..() methods provided by the
GrailsUnitTestCase class. Here we will look at all the available methods in some detail, starting with the all-purpose
mockFor(). But before we do, there is a very important point to make: using these methods ensures that any changes you make to the given classes do not leak into other tests! This is a common and serious problem when you try to perform the mocking yourself via meta-class programming, but that headache just disappears as long as you use at least one of
mock..() methods on each class you want to mock.
General purpose mocking that allows you to set up either strict or loose demands on a class.This method is surprisingly intuitive to use. By default it will create a strict mock control object (one for which the order in which methods are called is important) that you can use to specify demands:
mockFor(class, loose = false)
Notice that you can mock static methods as well as instance ones simply by using the "static" property after "demand". You then specify the name of the method that you want to mock with an optional range as its argument. This range determines how many times you expect the method to be called, so if the number of invocations falls outside of that range (either too few or too many) then an assertion error will be thrown. If no range is specified, a default of "1..1" is assumed, i.e. that the method must be called exactly once.The last part of a demand is a closure representing the implementation of the mock method. The closure arguments should match the number and types of the mocked method, but otherwise you are free to add whatever you want in the body.As we mentioned before, if you want an actual mock instance of the class that you are mocking, then you need to call
def strictControl = mockFor(MyService) strictControl.demand.someMethod(0..2) { String arg1, int arg2 -> … } strictControl.demand.static.aStaticMethod {-> … }
mockControl.createMock(). In fact, you can call this as many times as you like to create as many mock instances as you need. And once you have executed the test method, you can call
mockControl.verify() to check whether the expected methods were actually called or not.Lastly, the call:
will create a mock control object that has only loose expectations, i.e. the order that methods are invoked does not matter.
def looseControl = mockFor(MyService, true)
mockDomain(class, testInstances = )Takes a class and makes mock implementations of all the domain class methods (both instance- and static-level) accessible on it.Mocking domain classes is one of the big wins from using the testing plugin. Manually doing it is fiddly at best, so it's great that mockDomain() takes that burden off your shoulders.In effect,
mockDomain() provides a lightweight version of domain classes in which the "database" is simply a list of domain instances held in memory. All the mocked methods (
save() ,
get() ,
findBy*() , etc.) work against that list, generally behaving as you would expect them to. In addition to that, both the mocked
save() and validate() methods will perform real validation (support for the unique constraint included!) and populate an errors object on the corresponding domain instance.There isn't much else to say other than that the plugin does not support the mocking of criteria or HQL queries. If you use either of those, simply mock the corresponding methods manually (for example with
mockFor() ) or use an integration test with real data.
mockForConstraintsTests(class, testInstances = )Highly specialised mocking for domain classes and command objects that allows you to check whether the constraints are behaving as you expect them to.Do you test your domain constraints? If not, why not? If your answer is that they don't need testing, think again. Your constraints contain logic and that logic is highly susceptible to bugs - the kind of bugs that can be tricky to track down (particularly as save() doesn't throw an exception when it fails). If your answer is that it's too hard or fiddly, that is no longer an excuse. Enter the
mockForConstraintsTests() method.This is like a much reduced version of the
mockDomain() method that simply adds a
validate() method to a given domain class. All you have to do is mock the class, create an instance with field values, and then call
validate(). You can then access the errors property on your domain instance to find out whether the validation failed or not. So if all we are doing is mocking the
validate() method, why the optional list of test instances? That is so that we can test unique constraints as you will soon see.So, suppose we have a simple domain class like so:
Don't worry about whether the constraints are sensible or not (they're not!), they are for demonstration only. To test these constraints we can do the following:
class Book { String title String author static constraints = { title(blank: false, unique: true) author(blank: false, minSize: 5) } }
You can probably look at that code and work out what's happening without any further explanation. The one thing we will explain is the way the errors property is used. First, it does return a real Spring
class BookTests extends GrailsUnitTestCase { void testConstraints() { def existingBook = new Book(title: "Misery", author: "Stephen King") mockForConstraintsTests(Book, [ existingBook ]) // Validation should fail if both properties are null. def book = new Book() assertFalse book.validate() assertEquals "nullable", book.errors["title"] assertEquals "nullable", book.errors["author"] // So let's demonstrate the unique and minSize constraints. book = new Book(title: "Misery", author: "JK") assertFalse book.validate() assertEquals "unique", book.errors["title"] assertEquals "minSize", book.errors["author"] // Validation should pass! book = new Book(title: "The Shining", author: "Stephen King") assertTrue book.validate() } }
Errors instance, so you can access all the properties and methods you would normally expect. Second, this particular
Errors object also has map/property access as shown. Simply specify the name of the field you are interested in and the map/property access will return the name of the constraint that was violated. Note that it is the constraint name , not the message code (as you might expect).That's it for testing constraints. One final thing we would like to say is that testing the constraints in this way catches a common error: typos in the "constraints" property! It is currently one of the hardest bugs to track down normally, and yet a unit test for your constraints will highlight the problem straight away.
mockLogging(class, enableDebug = false)Adds a mock "log" property to a class. Any messages passed to the mock logger are echoed to the console.
mockController(class)Adds mock versions of the dynamic controller properties and methods to the given class. This is typically used in conjunction with the
ControllerUnitTestCase class.
mockTagLib(class)Adds mock versions of the dynamic taglib properties and methods to the given class. This is typically used in conjunction with the
TagLibUnitTestCase class.
9.2 Integration TestingIntegration tests differ from unit tests in that you have full access to the Grails environment within the test. Grails will use an in-memory HSQLDB database for integration tests and clear out all the data from the database in between each test.One thing to bear in mind is that logging is enabled for your application classes, but that is different from logging in tests. So if you have something like this:
the "starting tests" message is logged using a different system to the one used by the application. Basically the
class MyServiceTests extends GroovyTestCase { void testSomething() { log.info "Starting tests" … } }
log property in the example above is an instance of
java.util.logging.Logger, which doesn't have exactly the same methods as the
log property injected into your application artifacts. For example, it doesn't have
debug() or
trace() methods, and the equivalent of
warn() is in fact
TransactionsThe integration tests run inside a database transaction by default, which is then rolled back at the end of the tests. This means that data saved during the tests is not persisted to the database. If you actually want to check transactional behaviour of your services and controllers, then you can disable a test's transaction by adding a
transactional property to your test case:
class MyServiceTests extends GroovyTestCase { static transactional = false void testMyTransactionalServiceMethod() { … } }
Testing ControllersTo test controllers you first have to understand the Spring Mock Library.Essentially Grails automatically configures each test with a MockHttpServletRequest, MockHttpServletResponse, and MockHttpSession which you can then use to perform your tests. For example consider the following controller:
The tests for this would be:
class FooController { def text = { render "bar" } def someRedirect = { redirect(action:"bar") } }
In the above case the response is an instance of
class FooControllerTests extends GroovyTestCase { void testText() { def fc = new FooController() fc.text() assertEquals "bar", fc.response.contentAsString } void testSomeRedirect() { def fc = new FooController() fc.someRedirect() assertEquals "/foo/bar", fc.response.redirectedUrl } }
MockHttpServletResponse which we can use to obtain the
contentAsString (when writing to the response) or the URL redirected to for example. These mocked versions of the Servlet API are, unlike the real versions, all completely mutable and hence you can set properties on the request such as the
contextPath and so on.Grails does not invoke interceptors or servlet filters automatically when calling actions during integration testing. You should test interceptors and filters in isolation, and via functional testing if necessary.
Testing Controllers with ServicesIf your controller references a service (or other Spring beans), you have to explicitly initialise the service from your test.Given a controller using a service:
The test for this would be:
class FilmStarsController {
def popularityService def update = {
// do something with popularityService
class FilmStarsTests extends GroovyTestCase { def popularityService void testInjectedServiceInController () { def fsc = new FilmStarsController() fsc.popularityService = popularityService fsc.update() } }
Testing Controller Command ObjectsWith command objects you just supply parameters to the request and it will automatically do the command object work for you when you call your action with no parameters:Given a controller using a command object:
You can then test it like this:
class AuthenticationController { def signup = { SignupForm form -> … } }
Grails auto-magically sees your call to
def controller = new AuthenticationController() controller.params.login = "marcpalmer" controller.params.password = "secret" controller.params.passwordConfirm = "secret" controller.signup()
signup() as a call to the action and populates the command object from the mocked request parameters. During controller testing, the
params are mutable with a mocked request supplied by Grails.
Testing Controllers and the render MethodThe render method allows you to render a custom view at any point within the body of an action. For instance, consider the example below:
In the above example the result of the model of the action is not available as the return value, but instead is stored within the
def save = { def book = Book(params) if(book.save()) { // handle } else { render(view:"create", model:[book:book]) } }
modelAndView property of the controller. The
modelAndView property is an instance of Spring MVC's ModelAndView class and you can use it to the test the result of an action:
def bookController = new BookController()
def model = bookController.modelAndView.model.book
Simulating Request DataIf you're testing an action that requires request data such as a REST web service you can use the Spring MockHttpServletRequest object to do so. For example consider this action which performs data binding from an incoming request:
If you wish the simulate the 'book' parameter as an XML request you could do something like the following:
def create = {
[book: new Book(params['book']) ]
The same can be achieved with a JSON request:
void testCreateWithXML() { def controller = new BookController() controller.request.contentType = 'text/xml' controller.request.content = '''<?xml version="1.0" encoding="ISO-8859-1"?> <book> <title>The Stand</title> … </book> '''.getBytes() // note we need the bytes def model = controller.create() assert model.book assertEquals "The Stand", model.book.title }
void testCreateWithJSON() { def controller = new BookController() controller.request.contentType = "text/json" controller.request.content = '{"id":1,"class":"Book","title":"The Stand"}'.getBytes() def model = controller.create() assert model.book assertEquals "The Stand", model.book.title }
With JSON don't forget theFor more information on the subject of REST web services see the section on REST.
classproperty to specify the name the target type to bind too. In the XML this is implicit within the name of the
<book>node, but with JSON you need this property as part of the JSON packet.
Testing Web FlowsTesting Web Flows requires a special test harness called
grails.test.WebFlowTestCase which sub classes Spring Web Flow's AbstractFlowExecutionTests class.
Subclasses of For example given this trivial flow:
WebFlowTestCase must be integration tests
You need to tell the test harness what to use for the "flow definition". This is done via overriding the abstract
class ExampleController { def exampleFlow = { start { on("go") { flow.hello = "world" }.to "next" } next { on("back").to "start" on("go").to "subber" } subber { subflow(action: "sub") on("end").to("end") } end() } def subFlow = { subSubflowState { subflow(controller: "other", action: "otherSub") on("next").to("next") } … } }
If you need to specify the flow id you can do so by overriding the getFlowId method otherwise the default is
class ExampleFlowTests extends grails.test.WebFlowTestCase { def getFlow() { new ExampleController().exampleFlow } … }
If the flow under test calls any subflows, these (or mocks) need to be registered before the calling flow :
class ExampleFlowTests extends grails.test.WebFlowTestCase { String getFlowId() { "example" } … }
Once this is done in your test you need to kick off the flow with the
protected void setUp() { super.setUp() registerFlow("other/otherSub") { // register a simplified mock start { on("next").to("end") } end() } registerFlow("example/sub", new ExampleController().subFlow) // register the original subflow }
startFlow method:
To trigger and event you need to use the
void testExampleFlow() { def viewSelection = startFlow() … }
signalEvent method:
Here we have signaled to the flow to execute the event "go" this causes a transition to the "next" state. In the example a transition action placed a
void testExampleFlow() { … signalEvent("go") assert "next" == flowExecution.activeSession.state.id assert "world" == flowScope.hello }
hello variable into the flow scope.
Testing Tag LibrariesTesting tag libraries is actually pretty trivial because when a tag is invoked as a method it returns its result as a string. So for example if you have a tag library like this:
The tests would look like:
class FooTagLib { def bar = { attrs, body -> out << "<p>Hello World!</p>" } def bodyTag = { attrs, body -> out << "<${attrs.name}>" out << body() out << "</${attrs.name}>" } }
Notice that for the second example,
class FooTagLibTests extends GroovyTestCase { void testBarTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bar(null,null).toString() } void testBodyTag() { assertEquals "<p>Hello World!</p>", new FooTagLib().bodyTag(name:"p") { "Hello World!" }.toString() } }
testBodyTag, we pass a block that returns the body of the tag. This is handy for representing the body as a String.
Testing Tag Libraries with GroovyPagesTestCaseIn addition to doing simply testing of tag libraries like the above you can also use the
grails.test.GroovyPagesTestCase class to test tag libraries.The
GroovyPagesTestCase class is a sub class of the regular
GroovyTestCase class and provides utility methods for testing the output of a GSP rendering.
As an example given a date formatting tag library such as the one below:
GroovyPagesTestCase can only be used in an integration test.
This can be easily tested as follows:
class FormatTagLib {
def dateFormat = { attrs, body ->
out << new java.text.SimpleDateFormat(attrs.format) << attrs.date
You can also obtain the result of a GSP using the
class FormatTagLibTests extends GroovyPagesTestCase { void testDateFormat() { def template = '<g:dateFormat format="dd-MM-yyyy" date="${myDate}" />' def testDate = … // create the date assertOutputEquals( '01-01-2008', template, [myDate:testDate] ) } }
applyTemplate method of the
GroovyPagesTestCase class:
class FormatTagLibTests extends GroovyPagesTestCase { void testDateFormat() { def template = '<g:dateFormat format="dd-MM-yyyy" date="${myDate}" />' def testDate = … // create the date def result = applyTemplate( template, [myDate:testDate] ) assertEquals '01-01-2008', result } }
Testing Domain ClassesTesting domain classes is typically a simple matter of using the GORM API, however there are some things to be aware of. Firstly, if you are testing queries you will often need to "flush" in order to ensure the correct state has been persisted to the database. For example take the following example:
This test will actually fail, because calling save does not actually persist the
void testQuery() { def books = [ new Book(title:"The Stand"), new Book(title:"The Shining")] books*.save() assertEquals 2, Book.list().size() }
Book instances when called. Calling
save merely indicates to Hibernate that at some point in the future these instances should be persisted. If you wish to commit changes immediately you need to "flush" them:
In this case since we're passing the argument
void testQuery() { def books = [ new Book(title:"The Stand"), new Book(title:"The Shining")] books*.save(flush:true) assertEquals 2, Book.list().size() }
flush with a value of
true the updates will be persisted immediately and hence will be available to the query later on.
9.3 Functional TestingFunctional tests involve making HTTP requests against the running application and verifying the resultant behaviour. Grails does not ship with any support for writing functional tests directly, but there are several plugins available for this.
Canoo Webtest- http://grails.org/plugin/webtest
G-Func- http://grails.org/plugin/functional-test
Selenium-RC- http://grails.org/plugin/selenium-rc
WebDriver- http://grails.org/plugin/webdriver
Geb- http://grails.org/plugin/geb
Common OptionsThere are options that are common to all plugins that control how the Grails application is launched, if at all.
-inline option specifies that the grails application should be started inline (i.e. like
run-app).This option is implicitly set unless the
baseUrl or
war options are set
-war option specifies that the grails application should be packaged as a war and started. This is useful as it tests your application in a production like state, but it has a longer startup time than the
-inline option. It also runs the war in a forked JVM, meaning that you cannot access any internal application objects.
Note that the same build/config options for the run-war command apply to functional testing against the WAR.
grails test-app functional: -war
-https option results in the application being able to receive https requests as well as http requests. It is compatible with both the
-inline and
-war options.
Note that this does not change the test base url to be https, it will still be http unless the
grails test-app functional: -https
-httpsBaseUrl option is also given.
-httpsBaseUrl causes the implicit base url to be used for tests to be a https url.
This option is ignored if the
grails test-app functional: -httpsBaseUrl
-baseUrl option is given.
baseUrl option allows the base url for tests to be specified.
This option will prevent the local grails application being started unless
grails test-app functional: -baseUrl=http://mycompany.com/grailsapp
-inline or
-war are given as well. If you want to use a custom base url, but still want to test against the local Grails application you must specify one of either the
-inline or
-war options.
10. InternationalizationGrails supports Internationalization (i18n) out of the box through the underlying Spring MVC support for internationalization. With Grails you are able to customize the text that appears in any view based on the users Locale. To quote the javadoc for the Locale class in Java:
A Locale object represents a specific geographical, political, or cultural region. An operation that requires a Locale to perform its task is called locale-sensitive and uses the Locale to tailor information for the user. For example, displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country, region, or culture.A Locale is made up of a language code and a country code. For example "en_US" is the code for US english, whilst "en_GB" is the for British English.
10.1 Understanding Message BundlesNow that you have an idea of locales, to take advantage of them in Grails you have to create message bundles that contain the different languages that you wish to render. Message bundles in Grails are located inside the
grails-app/i18n directory and are simple Java properties files.Each bundle starts with the name
messages by convention and ends with the locale. Grails ships with a bunch of built in message bundles for a whole range of languages within the
grails-app/i18n directory. For example:
By default Grails will look in
messages.properties messages_de.properties messages_es.properties etc.
messages.properties for messages, unless the user has specified a custom locale. You can create your own message bundle by simply creating a new properties file that ends with the locale you are interested. For example
messages_en_GB.properties for British English.
10.2 Changing LocalesBy default the user locale is detected from the incoming
Accept-Language header. However, you can provide users the capability to switch locales by simply passing a parameter called
lang to Grails as a request parameter:
Grails will automatically switch the user locale and store it in a cookie so subsequent requests will have the new header.
10.3 Reading Messages
Reading Messages in the ViewThe most common place that you need messages is inside the view. To read messages from the view just use the message tag:
As long as you have a key in your
<g:message code="my.localized.content" />
messages.properties (with appropriate locale suffix) such as the one below then Grails will look-up the message:
Note that sometimes you may need to pass arguments to the message. This is also possible with the
my.localized.content=Hola, Me llamo John. Hoy es domingo.
message tag:
And then use positional parameters in the message:
<g:message code="my.localized.content" args="${ ['Juan', 'lunes'] }" />
my.localized.content=Hola, Me llamo {0}. Hoy es {1}.
Reading Messages in Controllers and Tag LibrariesSince you can invoke tags as methods from controllers it is also trivial to read messages within in a controller:
The same technique can be used on tag libraries, but note if your tag library has a different namespace then you will need to
def show = {
def msg = message(code:"my.localized.content", args:['Juan', 'lunes'])
g. prefix:
def myTag = { attrs, body ->
def msg = g.message(code:"my.localized.content", args:['Juan', 'lunes'])
10.4 Scaffolding and i18nGrails does not ship with i18n aware scaffolding templates to generate the controller and views. However, i18n aware templates are available via the i18n templates plugin. The templates are identical to the default scaffolding templates, except that they are i18n aware using the message tag for labels, buttons etc.To get started install the i18n templates with the following command:
Then refer to the reference on the wiki which explains how to use the i18n templates.
grails install-plugin i18n-templates
11. SecurityGrails is no more or less secure than Java Servlets. However, Java servlets (and hence Grails) are extremely secure and largely immune to common buffer overrun and malformed URL exploits due to the nature of the Java Virtual Machine underpinning the code.Web security problems typically occur due to developer naivety or mistakes, and there is a little Grails can do to avoid common mistakes and make writing secure applications easier to write.
What Grails Automatically DoesGrails has a few built in safety mechanisms by default.
- All standard database access via GORM domain objects is automatically SQL escaped to prevent SQL injection attacks
- The default scaffolding templates HTML escape all data fields when displayed
- Grails link creating tags (link, form, createLink, createLinkTo and others) all use appropriate escaping mechanisms to prevent code injection
- Grails provides codecs to allow you to trivially escape data when rendered as HTML, JavaScript and URLs to prevent injection attacks here.
11.1 Securing Against Attacks
SQL injectionHibernate, which is the technology underlying GORM domain classes, automatically escapes data when committing to database so this is not an issue. However it is still possible to write bad dynamic HQL code that uses unchecked request parameters. For example doing the following is vulnerable to HQL injection attacks:
Do not do this. If you need to pass in parameters use named or positional parameters instead:
def vulnerable = { def books = Book.find("from Book as b where b.title ='" + params.title + "'") }
def safe = {
def books = Book.find("from Book as b where b.title =?", [params.title])
PhishingThis really a public relations issue in terms of avoiding hijacking of your branding and a declared communication policy with your customers. Customers need to know how to identify bonafide emails received.
XSS - cross-site scripting injectionIt is important that your application verifies as much as possible that incoming requests were originated from your application and not from another site. Ticketing and page flow systems can help this and Grails' support for Spring Web Flow includes security like this by default.It is also important to ensure that all data values rendered into views are escaped correctly. For example when rendering to HTML or XHTML you must call encodeAsHTML on every object to ensure that people cannot maliciously inject JavaScript or other HTML into data or tags viewed by others. Grails supplies several Dynamic Encoding Methods for this purpose and if your output escaping format is not supported you can easily write your own codec.You must also avoid the use of request parameters or data fields for determining the next URL to redirect the user to. If you use a
successURL parameter for example to determine where to redirect a user to after a successful login, attackers can imitate your login procedure using your own site, and then redirect the user back to their own site once logged in, potentially allowing JS code to then exploit the logged-in account on the site.
HTML/URL injectionThis is where bad data is supplied such that when it is later used to create a link in a page, clicking it will not cause the expected behaviour, and may redirect to another site or alter request parameters.HTML/URL injection is easily handled with the codecs supplied by Grails, and the tag libraries supplied by Grails all use encodeAsURL where appropriate. If you create your own tags that generate URLs you will need to be mindful of doing this too.
Denial of serviceLoad balancers and other appliances are more likely to be useful here, but there are also issues relating to excessive queries for example where a link is created by an attacker to set the maximum value of a result set so that a query could exceed the memory limits of the server or slow the system down. The solution here is to always sanitize request parameters before passing them to dynamic finders or other GORM query methods:
def safeMax = Math.max(params.max?.toInteger(), 100) // limit to 100 results return Book.list(max:safeMax)
Guessable IDsMany applications use the last part of the URL as an "id" of some object to retrieve from GORM or elsewhere. Especially in the case of GORM these are easily guessable as they are typically sequential integers.Therefore you must assert that the requesting user is allowed to view the object with the requested id before returning the response to the user.Not doing this is "security through obscurity" which is inevitably breached, just like having a default password of "letmein" and so on.You must assume that every unprotected URL is publicly accessible one way or another.
11.2 Encoding and Decoding ObjectsGrails supports the concept of dynamic encode/decode methods. A set of standard codecs are bundled with Grails. Grails also supports a simple mechanism for developers to contribute their own codecs that will be recognized at runtime.
Codec ClassesA Grails codec class is a class that may contain an encode closure, a decode closure or both. When a Grails application starts up the Grails framework will dynamically load codecs from the
grails-app/utils/ directory.The framework will look under
grails-app/utils/ for class names that end with the convention
Codec. For example one of the standard codecs that ship with Grails is
HTMLCodec.If a codec contains an
encode property assigned a block of code Grails will create a dynamic
encode method and add that method to the Object class with a name representing the codec that defined the encode closure. For example, the
HTMLCodec class defines an
encode block so Grails will attach that closure to the
Object class with the name
HTMLCodec and
URLCodec classes also define a
decode block so Grails will attach those with the names
decodeHTML and
decodeURL. Dynamic codec methods may be invoked from anywhere in a Grails application. For example, consider a case where a report contains a property called 'description' and that description may contain special characters that need to be escaped to be presented in an HTML document. One way to deal with that in a GSP is to encode the description property using the dynamic encode method as shown below:
Decoding is performed using
value.decodeHTML() syntax.
Standard CodecsHTMLCodecThis codec perfoms HTML escaping and unescaping, so that values you provide can be rendered safely in an HTML page without creating any HTML tags or damaging the page layout. For example, given a value "Don't you know that 2 > 1?" you wouldn't be able to show this safely within an HTML page because the > will look like it closes a tag, which is especially bad if you render this data within an attribute, such as the value attribute of an input field.Example of usage:
<input name="comment.message" value="${comment.message.encodeAsHTML()}"/>
Note that the HTML encoding does not re-encode apostrophe/single quote so you must use double quotes on attribute values to avoid text with apostrophes messing up your page.URLCodecURL encoding is required when creating URLs in links or form actions, or any time data may be used to create a URL. It prevents illegal characters getting into the URL to change its meaning, for example a "Apple & Blackberry" is not going to work well as a parameter in a GET request as the ampersand will break the parsing of parameters.Example of usage:
Base64CodecPerforms Base64 encode/decode functions. Example of usage:
<a href="/mycontroller/find?searchKey=${lastSearch.encodeAsURL()}">Repeat last search</a>
JavaScriptCodecWill escape Strings so they can be used as valid JavaSctipt strings. Example of usage:
Your registration code is: ${user.registrationCode.encodeAsBase64()}
HexCodecWill encode byte arrays or lists of integers to lowercase hexadecimal strings, and can decode hexadecimal strings into byte arrays. Example of usage:
Element.update('${elementId}', '${render(template: "/common/message").encodeAsJavaScript()}')
MD5CodecWill use the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:
Selected colour: #${[255,127,255].encodeAsHex()}
MD5BytesCodecWill use the MD5 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:
Your API Key: ${user.uniqueID.encodeAsMD5()}
SHA1CodecWill use the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:
byte[] passwordHash = params.password.encodeAsMD5Bytes()
SHA1BytesCodecWill use the SHA1 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:
Your API Key: ${user.uniqueID.encodeAsSHA1()}
SHA256CodecWill use the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a lowercase hexadecimal string. Example of usage:
byte[] passwordHash = params.password.encodeAsSHA1Bytes()
SHA256BytesCodecWill use the SHA256 algorithm to digest byte arrays or lists of integers, or the bytes of a string (in default system encoding), as a byte array. Example of usage:
Your API Key: ${user.uniqueID.encodeAsSHA256()}
byte[] passwordHash = params.password.encodeAsSHA256Bytes()
Custom CodecsApplications may define their own codecs and Grails will load them along with the standard codecs. A custom codec class must be defined in the
grails-app/utils/ directory and the class name must end with
Codec. The codec may contain a
encode block, a
decode block or both. The block should expect a single argument which will be the object that the dynamic method was invoked on. For Example:
With the above codec in place an application could do something like this:
class PigLatinCodec { static encode = { str -> // convert the string to piglatin and return the result } }
11.3 AuthenticationAlthough there is no current default mechanism for authentication as it is possible to implement authentication in literally thousands of different ways. It is however, trivial to implement a simple authentication mechanism using either interceptors or filters.Filters allow you to apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class called
Here the
class SecurityFilters { def filters = { loginCheck(controller:'*', action:'*') { before = { if(!session.user && actionName != "login") { redirect(controller:"user",action:"login") return false } } } } }
loginCheck filter will intercept execution before an action executed and if their is no user in the session and the action being executed is not the
login action then redirect to the
login action.The
login action itself is trivial too:
def login = { if(request.get) render(view:"login") else { def u = User.findByLogin(params.login) if(u) { if(u.password == params.password) { session.user = u redirect(action:"home") } else { render(view:"login", model:[message:"Password incorrect"]) } } else { render(view:"login", model:[message:"User not found"]) } } }
11.4 Security Plug-insIf you need more advanced functionality beyond simple authentication such as authorization, roles etc. then you may want to consider using one of the available security plug-ins.
11.4.1 Spring SecurityThe Spring Security plugins are built on the Spring Security project which provides a flexible, extensible framework for building all sorts of authentication and authorization schemes. The plugins are modular so you can install just the functionality that you need for your application. There is a Core plugin which supports form-based authentication, encrypted/salted passwords, HTTP Basic authentication, etc. and secondary dependent plugins provide alternate functionality such as OpenID authentication, ACL support, etc.See the plugin page for basic information and the user guide for detailed information.
11.4.2 ShiroShiro is a Java POJO oriented security framework that provides a default domain model that models realms, users, roles and permissions. With Shiro you have to extends a controller base called called
JsecAuthBase in each controller you want secured and then provide an
accessControl block to setup the roles. An example below:
For more information on the Shiro plugin refer to the documentation.
class ExampleController extends JsecAuthBase { static accessControl = { // All actions require the 'Observer' role. role(name: 'Observer') // The 'edit' action requires the 'Administrator' role. role(name: 'Administrator', action: 'edit') // Alternatively, several actions can be specified. role(name: 'Administrator', only: [ 'create', 'edit', 'save', 'update' ]) } … }
12. Plug-insGrails provides a number of extension points that allow you to extend anything from the command line interface to the runtime configuration engine. The following sections detail how to go about it.
12.1 Creating and Installing Plug-ins
Creating PluginsCreating a Grails plugin is a simple matter of running the command:
This will create a plugin project for the name you specify. Say for example you run
grails create-plugin [PLUGIN NAME]
grails create-plugin example. This would create a new plugin project called
example.The structure of a Grails plugin is exactly the same as a regular Grails project's directory structure, except that in the root of the plugin directory you will find a plugin Groovy file called the "plugin descriptor".Being a regular Grails project has a number of benefits in that you can immediately get going testing your plugin by running:
The plugin descriptor itself ends with the convention
grails run-app
GrailsPlugin and is found in the root of the plugin project. For example:
All plugins must have this class in the root of their directory structure to be valid. The plugin class defines the version of the plugin and optionally various hooks into plugin extension points (covered shortly).You can also provide additional information about your plugin using several special properties:
class ExampleGrailsPlugin { def version = 0.1 … }
title- short one sentence description of your plugin
version- The version of your problem. Valid versions are for example "0.1", "0.2-SNAPSHOT", "0.1.4" etc.
grailsVersion- The version of version range of Grails that the plugin supports. eg. "1.1 > *"
author- plug-in author's name
authorEmail- plug-in author's contact e-mail
description- full multi-line description of plug-in's features
documentation- URL where plug-in's documentation can be found
class QuartzGrailsPlugin { def version = "0.1" def grailsVersion = "1.1 > *" def author = "Sergey Nebolsin" def authorEmail = "[email protected]" def title = "This plugin adds Quartz job scheduling features to Grails application." def description = ''' Quartz plugin allows your Grails application to schedule jobs to be executed using a specified interval or cron expression. The underlying system uses the Quartz Enterprise Job Scheduler configured via Spring, but is made simpler by the coding by convention paradigm. ''' def documentation = "http://grails.org/Quartz+plugin" … }
Installing & Distributing PluginsTo distribute a plugin you need to navigate to its root directory in a terminal window and then type:
This will create a zip file of the plugin starting with
grails package-plugin
grails- then the plugin name and version. For example with the example plug-in created earlier this would be
grails-example-0.1.zip. The
package-plugin command will also generate
plugin.xml file which contains machine-readable information about plugin's name, version, author, and so on.Once you have a plugin distribution file you can navigate to a Grails project and type:
If the plugin is hosted on a remote HTTP server you can also do:
grails install-plugin /path/to/plugin/grails-example-0.1.zip
grails install-plugin http://myserver.com/plugins/grails-example-0.1.zip
Notes on excluded ArtefactsAlthough the create-plugin command creates certain files for you so that the plug-in can be run as a Grails application, not all of these files are included when packaging a plug-in. The following is a list of artefacts created, but not included by package-plugin:
- Everything within
WEB-INF it is recommended you use the
_Install.groovy script (covered later), which is executed when a plug-in is installed, to provide such artefacts. In addition, although
UrlMappings.groovy is excluded you are allowed to include a
UrlMappings definition with a different name, such as
Specifying Plugin LocationsAn application can load plugins from anywhere on the file system, even if they have not been installed. Simply add the location of the (unpacked) plugin to the application's
grails-app/conf/BuildConfig.groovy file:
This is particularly useful in two cases:
// Useful to test plugins you are developing. grails.plugin.location.jsecurity = "/home/dilbert/dev/plugins/grails-jsecurity"// Useful for modular applications where all plugins and // applications are in the same directory. grails.plugin.location.'grails-ui' = "../grails-grails-ui"
- You are developing a plugin and want to test it in a real application without packaging and installing it first.
- You have split an application into a set of plugins and an application, all in the same "super-project" directory.
12.2 Plugin Repositories
Distributing Plugins in the Grails Central Plugins RepositoryThe preferred way of plugin distribution is to publish your under Grails Plugins Repository. This will make your plugin visible to the list-plugins command:
Which lists all plugins in the Grails Plugin repository and also the plugin-info command:
grails list-plugins
Which outputs more information based on the meta info entered into the plug-in descriptor.
grails plugin-info [plugin-name]
If you have created a Grails plugin and want it to be hosted in the central repository take a look at the wiki page , which details how to go about releasing your plugin in the repository.When you have access to the Grails Plugin repository to release your plugin you simply have to execute the release-plugin command:
This will automatically commit changes to SVN, do some tagging and make your changes available via the list-plugins command.
grails release-plugin
Configuring Additional RepositoriesThe way in which you configure repositories in Grails differs between Grails versions. For version of Grails 1.2 and earlier please refer to the Grails 1.2 documentation on the subject. The following sections cover Grails 1.3 and above.Grails 1.3 and above use Ivy under the hood to resolve plugin dependencies. The mechanism for defining additional plugin repositories is largely the same as defining repositories for JAR dependencies. For example you can define a remote Maven repository that contains Grails plugins using the following syntax in
You can also define a SVN-based Grails repository (such as the one hosted at http://plugins.grails.org/) using the
repositories {
mavenRepo "http://repository.codehaus.org"
grailsRepo method:
There is a shortcut to setup the Grails central repository:
repositories {
grailsRepo "http://myserver/mygrailsrepo"
The order in which plugins are resolved is based on the ordering of the repositories. So for example in this case the Grails central repository will be searched last:
repositories { grailsCentral() }
All of the above examples use HTTP, however you can specify any Ivy resolver to resolve plugins with. Below is an example that uses an SSH resolver:
repositories {
grailsRepo "http://myserver/mygrailsrepo"
The above example defines an artifact pattern which tells Ivy how to resolve a plugin zip file. For a more detailed explanation on Ivy patterns see the relevant section in the Ivy user guide.
def sshResolver = new SshResolver(user:"myuser", host:"myhost.com") sshResolver.addArtifactPattern("/path/to/repo/grails-[artifact]/tags/LATEST_RELEASE/grails-[artifact]-[revision].[ext]") sshResolver.latestStrategy = new org.apache.ivy.plugins.latest.LatestTimeStrategy() sshResolver.changingPattern = ".*SNAPSHOT" sshResolver.setCheckmodified(true)
Publishing to Maven Compatible RepositoriesIn general it is recommended for Grails 1.3 and above to use standard Maven-style repositories to self host plugins. The benefits of doing so include the ability for existing tooling and repository managers to interpret the structure of a Maven repository. In addition Maven compatible repositories are not tied to SVN as Grails repositories are.In order to publish a plugin to a Maven repository you need to use the Maven publisher plugin. Please refer to the section of the Maven deployment user guide on the subject.
Publishing to Grails Compatible RepositoriesTo publish a Grails plugin to a Grails compatible repository you specify the
grails.plugin.repos.distribution.myRepository setting within the grails-app/conf/BuildConfig.groovy file:
You can also provide this settings in the USER_HOME/.grails/settings.groovy file if you prefer to share the same settings across multiple projects.Once this is done you need to use the
repository argument of the
release-plugin command to specify the repository you want to release the plugin into:
grails release-plugin -repository=myRepository
12.3 Understanding a Plug-ins StructureAs as mentioned previously, a plugin is merely a regular Grails application with a contained plug-in descriptors. However when installed, the structure of a plugin differs slightly. For example, take a look at this plugin directory structure:
Essentially when a plugin is installed into a project, the contents of the
+ grails-app + controllers + domain + taglib etc. + lib + src + java + groovy + web-app + js + css
grails-app directory will go into a directory such as
plugins/example-1.0/grails-app. They will not be copied into the main source tree. A plugin never interferes with a project's primary source tree.Dealing with static resources is slightly different. When developing a plugin, just like an application, all static resources can go in the
web-app directory. You can then link to static resources just like in an application (example below links to a javascript source):
When you run the plugin in development mode the link to the resource will resolve to something like
<g:resource dir="js" file="mycode.js" />
/js/mycode.js. However, when the plugin is installed into an application the path will automatically change to something like
/plugin/example-0.1/js/mycode.js and Grails will deal with making sure the resources are in the right place.There is a special
pluginContextPath variable that can be used whilst both developing the plugin and when in the plugin is installed into the application to find out what the correct path to the plugin is.At runtime the
pluginContextPath variable will either evaluate to an empty string or
/plugins/example depending on whether the plugin is running standalone or has been installed in an applicationJava & Groovy code that the plugin provides within the lib and
src/java and
src/groovy directories will be compiled into the main project's
web-app/WEB-INF/classes directory so that they are made available at runtime.
12.4 Providing Basic Artefacts
Adding a new ScriptA plugin can add a new script simply by providing the relevant Gant script within the scripts directory of the plugin:
+ MyPlugin.groovy + scripts <-- additional scripts here + grails-app + controllers + services + etc. + lib
Adding a new Controller, Tag Library or ServiceA plugin can add a new controller, tag libraries, service or whatever by simply creating the relevant file within the
grails-app tree. Note that when the plugin is installed it will be loaded from where it is installed and not copied into the main application tree.
+ ExamplePlugin.groovy + scripts + grails-app + controllers <-- additional controllers here + services <-- additional services here + etc. <-- additional XXX here + lib
Providing Views, Templates and View resolutionWhen a plug-in provides a controller it may also provide default views to be rendered. This is an excellent way to modularize your application through plugins. The way it works is that Grails' view resolution mechanism will first look the view in the application it is installed into and if that fails will attempt to look for the view within the plug-in.For example given a
AmazonGrailsPlugin plug-n provided controller called
BookController if the action being executed is
list, Grails will first look for a view called
grails-app/views/book/list.gsp then if that fails will look for the same view relative to the plug-in.Note however that if the view uses templates that are also provided by the plugin then the following syntax may be necessary:
Note the usage of the
<g:render template="fooTemplate" plugin="amazon"/>
plugin attribute, which contains the name of the plugin where the template resides. If this is not specified then Grails will look for the template relative to the application.
Excluded ArtefactsNote that by default, when packaging a plug-in, Grails will excludes the following files from the packaged plug-in:
- grails-app/conf/DataSource.groovy
- grails-app/conf/UrlMappings.groovy
- Everything under web-app/WEB-INF
web-app/WEB-INF directory it is recommended that you modify the plug-in's
scripts/_Install.groovy Gant script to install these artefacts into the target project's directory tree.In addition, the default
UrlMappings.groovy file is excluded to avoid naming conflicts, however you are free to add a UrlMappings definition under a different name which will be included. For example a file called
grails-app/conf/BlogUrlMappings.groovy is fine.Additionally the list of includes is extensible via the
pluginExcludes property:
This is useful, for example, if you want to include demo or test resources in the plugin repository, but not include them in the final distribution.
// resources that are excluded from plugin packaging
def pluginExcludes = [
12.5 Evaluating ConventionsBefore moving onto looking at providing runtime configuration based on conventions you first need to understand how to evaluated those conventions from a plug-in. Essentially every plugin has an implicit
application variable which is an instance of the GrailsApplication interface.The
GrailsApplication interface provides methods to evaluate the conventions within the project and internally stores references to all classes within a GrailsApplication using the GrailsClass interface.A
GrailsClass represents a physical Grails resources such as a controller or a tag library. For example to get all
GrailsClass instances you can do:
There are a few "magic" properties that the
application.allClasses.each { println it.name }
GrailsApplication instance possesses that allow you to narrow the type of artefact you are interested in. For example if you only want to controllers you can do:
The dynamic method conventions are as follows:
application.controllerClasses.each { println it.name }
*Classes- Retrieves all the classes for a particular artefact name. Example
get*Class- Retrieves a named class for a particular artefact. Example
is*Class- Returns true if the given class is of the given artefact type. Example
GrailsClass interface itself provides a number of useful methods that allow you to further evaluate and work with the conventions. These include:
getPropertyValue- Gets the initial value of the given property on the class
hasProperty- Returns true if the class has the specified property
newInstance- Creates a new instance of this class.
getName- Returns the logical name of the class in the application without the trailing convention part if applicable
getShortName- Returns the short name of the class without package prefix
getFullName- Returns the full name of the class in the application with the trailing convention part and with the package name
getPropertyName- Returns the name of the class as a property name
getLogicalPropertyName- Returns the logical property name of the class in the application without the trailing convention part if applicable
getNaturalName- Returns the name of the property in natural terms (eg. 'lastName' becomes 'Last Name')
getPackageName- Returns the package name
12.6 Hooking into Build Events
Post-Install Configuration and Participating in UpgradesGrails plug-ins can do post-install configuration and participate in application upgrade process (the upgrade command). This is achieved via two specially named scripts under
scripts directory of the plugin -
_Install.groovy and
_Install.groovy is executed after the plugin has been installed and
_Upgrade.groovy is executed each time the user upgrades his application with upgrade command.These scripts are normal Gant scripts so you can use the full power of Gant. An addition to the standard Gant variables is the
pluginBasedir variable which points at the plugin installation basedir.As an example the below
_Install.groovy script will create a new directory type under the
grails-app directory and install a configuration template:
Ant.mkdir(dir:"${basedir}/grails-app/jobs") Ant.copy(file:"${pluginBasedir}/src/samples/SamplePluginConfiguration.groovy", todir:"${basedir}/grails-app/conf")// To access Grails home you can use following code: // Ant.property(environment:"env") // grailsHome = Ant.antProject.properties."env.GRAILS_HOME"
Scripting eventsIt is also possible to hook into command line scripting events through plug-ins. These are events triggered during execution of Grails target and plugin scripts.For example, you can hook into status update output (i.e. "Tests passed", "Server running") and the creation of files or artefacts.A plug-in merely has to provide an
_Events.groovy script to listen to the required events. Refer the documentation on Hooking into Events for further information.
12.7 Hooking into Runtime ConfigurationGrails provides a number of hooks to leverage the different parts of the system and perform runtime configuration by convention.
Hooking into the Grails Spring configurationFirst, you can hook in Grails runtime configuration by providing a property called
doWithSpring which is assigned a block of code. For example the following snippet is from one of the core Grails plugins that provides i18n support:
This plugin sets up the Grails
import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.context.support.ReloadableResourceBundleMessageSource;class I18nGrailsPlugin { def version = 0.1 def doWithSpring = { messageSource(ReloadableResourceBundleMessageSource) { basename = "WEB-INF/grails-app/i18n/messages" } localeChangeInterceptor(LocaleChangeInterceptor) { paramName = "lang" } localeResolver(CookieLocaleResolver) } }
messageSource bean and a couple of other beans to manage Locale resolution and switching. It using the Spring Bean Builder syntax to do so.
Participating in web.xml GenerationGrails generates the
WEB-INF/web.xml file at load time, and although plugins cannot change this file directly, they can participate in the generation of the file. Essentially a plugin can provide a
doWithWebDescriptor property that is assigned a block of code that gets passed the
web.xml as a
GPathResult.Consider the below example from the
Here the plugin goes through gets a reference to the last
def doWithWebDescriptor = { webXml -> def mappingElement = webXml.'servlet-mapping' def lastMapping = mappingElement[mappingElement.size()-1] lastMapping + { 'servlet-mapping' { 'servlet-name'("grails") 'url-pattern'("*.dispatch") } } }
<servlet-mapping> element and appends Grails' servlet to the end of it using XmlSlurper's ability to programmatically modify XML using closures and blocks.
Doing Post Initialisation ConfigurationSometimes it is useful to be able do some runtime configuration after the Spring ApplicationContext has been built. In this case you can define a
doWithApplicationContext closure property.
class SimplePlugin { def name="simple" def version = 1.1 def doWithApplicationContext = { appCtx -> SessionFactory sf = appCtx.getBean("sessionFactory") // do something here with session factory } }
12.8 Adding Dynamic Methods at Runtime
The BasicsGrails plugins allow you to register dynamic methods with any Grails managed or other class at runtime. New methods can only be added within a
doWithDynamicMethods closure of a plugin.For Grails managed classes like controllers, tag libraries and so forth you can add methods, constructors etc. using the ExpandoMetaClass mechanism by accessing each controller's MetaClass:
In this case we use the implicit application object to get a reference to all of the controller classes' MetaClass instances and then add a new method called
class ExamplePlugin {
def doWithDynamicMethods = { applicationContext ->
application.controllerClasses.each { controllerClass ->
controllerClass.metaClass.myNewMethod = {-> println "hello world" }
myNewMethod to each controller.
Alternatively, if you know before hand the class you wish the add a method to you can simple reference that classes
metaClass property:
In this example we add a new method
class ExamplePlugin { def doWithDynamicMethods = { applicationContext -> String.metaClass.swapCase = {-> def sb = new StringBuffer() delegate.each { sb << (Character.isUpperCase(it as char) ? Character.toLowerCase(it as char) : Character.toUpperCase(it as char)) } sb.toString() } assert "UpAndDown" == "uPaNDdOWN".swapCase() } }
swapCase to
java.lang.String directly by accessing its
Interacting with the ApplicationContextThe
doWithDynamicMethods closure gets passed the Spring
ApplicationContext instance. This is useful as it allows you to interact with objects within it. For example if you where implementing a method to interact with Hibernate you could use the
SessionFactory instance in combination with a
Also because of the autowiring and dependency injection capability of the Spring container you can implement more powerful dynamic constructors that use the application context to wire dependencies into your object at runtime:
import org.springframework.orm.hibernate3.HibernateTemplateclass ExampleHibernatePlugin { def doWithDynamicMethods = { applicationContext -> application.domainClasses.each { domainClass -> domainClass.metaClass.static.load = { Long id-> def sf = applicationContext.sessionFactory def template = new HibernateTemplate(sf) template.load(delegate, id) } } } }
Here we actually replace the default constructor with one that looks up prototyped Spring beans instead!
class MyConstructorPlugin { def doWithDynamicMethods = { applicationContext ->
application.domainClasses.each { domainClass ->
domainClass.metaClass.constructor = {->
return applicationContext.getBean(domainClass.name)
} }
12.9 Participating in Auto Reload Events
Monitoring Resources for ChangesOften it is valuable to monitor resources for changes and then reload those changes when they occur. This is how Grails implements advanced reloading of application state at runtime. For example, consider the below simplified snippet from the
ServicesPlugin that Grails comes with:
Firstly it defines a set of
class ServicesGrailsPlugin { … def watchedResources = "file:./grails-app/services/*Service.groovy" … def onChange = { event -> if(event.source) { def serviceClass = application.addServiceClass(event.source) def serviceName = "${serviceClass.propertyName}" def beans = beans { "$serviceName"(serviceClass.getClazz()) { bean -> bean.autowire = true } } if(event.ctx) { event.ctx.registerBeanDefinition(serviceName, beans.getBeanDefinition(serviceName)) } } } }
watchedResources as either a String or a List of strings that contain either the references or patterns of the resources to watch. If the watched resources is a Groovy file, when it is changed it will automatically be reloaded and passed into the
onChange closure inside the
event object.The
event object defines a number of useful properties:
event.source- The source of the event which is either the reloaded class or a Spring Resource
event.ctx- The Spring
event.plugin- The plugin object that manages the resource (Usually this)
event.application- The
ApplicationContext and so forth based on the conventions, etc. In the "Services" example above, a new services bean is re-registered with the
ApplicationContext when one of the service classes changes.
Influencing Other PluginsAs well as being able to react to changes that occur when a plugin changes, sometimes one plugin needs to "influence" another plugin.Take for example the Services & Controllers plugins. When a service is reloaded, unless you reload the controllers too, problems will occur when you try to auto-wire the reloaded service into an older controller Class.To get round this, you can specify which plugins another plugin "influences". What this means is that when one plugin detects a change, it will reload itself and then reload all influenced plugins. See this snippet from the
def influences = ['controllers']
Observing other pluginsIf there is a particular plugin that you would like to observe for changes but not necessary watch the resources that it monitors you can use the "observe" property:
In this case when a controller is changed you will also receive the event chained from the controllers plugin. It is also possible for a plugin to observe all loaded plugins by using a wildcard:
def observe = ["controllers"]
The Logging plugin does exactly this so that it can add the
def observe = ["*"]
log property back to any artefact that changes while the application is running.
12.10 Understanding Plug-in Load Order
Controlling Plug-in DependenciesPlug-ins often depend on the presence of other plugins and can also adapt depending on the presence of others. To cover this, a plugin can define two properties. The first is called
dependsOn. For example, take a look at this snippet from the Grails Hibernate plugin:
As the above example demonstrates the Hibernate plugin is dependent on the presence of 4 plugins: The
class HibernateGrailsPlugin { def version = 1.0 def dependsOn = [dataSource:1.0, domainClass:1.0, i18n:1.0, core: 1.0]}
dataSource plugin, The
domainClass plugin, the
i18n plugin and the
core plugin.Essentially the dependencies will be loaded first and then the Hibernate plugin. If all dependencies do not load, then the plugin will not load.The
dependsOn property also supports a mini expression language for specifying version ranges. A few examples of the syntax can be seen below:
When the wildcard * character is used it denotes "any" version. The expression syntax also excludes any suffixes such as -BETA, -ALPHA etc. so for example the expression "1.0 > 1.1" would match any of the following versions:
def dependsOn = [foo:"* > 1.0"] def dependsOn = [foo:"1.0 > 1.1"] def dependsOn = [foo:"1.0 > *"]
- 1.1
- 1.0
- 1.0.1
Controlling Load OrderUsing
dependsOn establishes a "hard" dependency in that if the dependency is not resolved, the plugin will give up and won't load. It is possible though to have a "weaker" dependency using the
loadAfter property:
Here the plugin will be loaded after the
def loadAfter = ['controllers']
controllers plugin if it exists, otherwise it will just be loaded. The plugin can then adapt to the presence of the other plugin, for example the Hibernate plugin has this code in the
doWithSpring closure:
Here the Hibernate plugin will only register an
if(manager?.hasGrailsPlugin("controllers")) { openSessionInViewInterceptor(OpenSessionInViewInterceptor) { flushMode = HibernateAccessor.FLUSH_MANUAL sessionFactory = sessionFactory } grailsUrlHandlerMapping.interceptors << openSessionInViewInterceptor }
OpenSessionInViewInterceptor if the
controllers plugin has been loaded. The manager variable is an instance of the GrailsPluginManager interface and it provides methods to interact with other plugins and the
GrailsPluginManager itself from any plugin.
13. Web ServicesWeb services are all about providing a web API onto your web application and are typically implemented in either SOAP or REST.
13.1 RESTREST is not really a technology in itself, but more an architectural pattern. REST is extremely simple and just involves using plain XML or JSON as a communication medium, combined with URL patterns that are "representational" of the underlying system and HTTP methods such as GET, PUT, POST and DELETE.Each HTTP method maps to an action. For example GET for retrieving data, PUT for creating data, POST for updating and so on. In this sense REST fits quite well with CRUD.
URL patternsThe first step to implementing REST with Grails is to provide RESTful URL mappings:
What this does is map the URI
static mappings = { "/product/$id?"(resource:"product") }
/product onto a
ProductController. Each HTTP method such as GET, PUT, POST and DELETE map to unique actions within the controller as outlined by the table below:
However, unlike the
"/product/$id"(controller:"product"){ action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] }
resource argument used previously, in this case Grails will not provide automatic XML or JSON marshaling for you unless you specify the
parseRequest argument in the URL mapping:
"/product/$id"(controller:"product", parseRequest:true){ action = [GET:"show", PUT:"update", DELETE:"delete", POST:"save"] }
HTTP MethodsIn the previous section you saw how you can easily define URL mappings that map specific HTTP methods onto specific controller actions. Writing a REST client that then sends a specific HTTP method is then trivial (example in Groovy's HTTPBuilder module):
However, issuing a request with a method other than
import groovyx.net.http.* import static groovyx.net.http.ContentType.JSONdef http = new HTTPBuilder("http://localhost:8080/amazon") http.request(Method.GET, JSON) { url.path = '/book/list' response.success = {resp, json -> json.books.each { book -> println book.title } } }
GET or
POST from a regular browser is not possible without some help from Grails. When defining a form you can specify an alternative method such as
Grails will send a hidden parameter called
<g:form controller="book" method="DELETE"> .. </g:form>
_method, which will be used as the request's HTTP method. Another alternative for changing the method for non-browser clients is to use the
X-HTTP-Method-Override to specify the alternative method name.
XML Marshaling - ReadingThe controller implementation itself can use Grails' XML marshaling support to implement the GET method:
Here what we do is if there is an
import grails.converters.* class ProductController { def show = { if(params.id && Product.exists(params.id)) { def p = Product.findByName(params.id) render p as XML } else { def all = Product.list() render all as XML } } .. }
id we search for the
Product by name and return it otherwise we return all Products. This way if we go to
/products we get all products, otherwise if we go to
/product/MacBook we only get a MacBook.
XML Marshalling - UpdatingTo support updates such as
PUT and
POST you can use the params object which Grails enhances with the ability to read an incoming XML packet. Given an incoming XML packet of:
You can read this XML packet using the same techniques described in the Data Binding section via the params object:
<?xml version="1.0" encoding="ISO-8859-1"?> <product> <name>MacBook</name> <vendor id="12"> <name>Apple</name> </vender> </product>
In this example by indexing into the
def save = { def p = new Product(params['product']) if(p.save()) { render p as XML } else { render p.errors } }
params object using the key
'product' we can automatically create and bind the XML using the constructor of the
Product class. An interesting aspect of the line:
Is that it requires no code changes to deal with a form submission that submits form data than it does to deal with an XML request. The exact same technique can be used with a JSON request too.
def p = new Product(params['product'])
If you require different responses to different clients (REST, HTML etc.) you can use content negotationThe
Product object is then saved and rendered as XML, otherwise an error message is produced using Grails' validation capabilities in the form:
<error> <message>The property 'title' of class 'Person' must be specified</message> </error>
13.2 SOAPThere are several plugins that add SOAP support to Grails depending on your preferred approach. For Contract First SOAP services there is a Spring WS plugin, whilst if you want to generate a SOAP API from Grails services there are several plugins that do this including:
- XFire plugin which uses the XFire SOAP stack
- CXF plugin which uses the CXF SOAP stack
- Axis2 plugin which uses Axis2
- Metro plugin which uses the Metro framework (and can also be used for Contract First)
exposes static property. The below example is taken from the XFire plugin:
The WSDL can then be accessed at the location:
class BookService { static expose=['xfire'] Book[] getBooks(){
Book.list() as Book[]
http://127.0.0.1:8080/your_grails_app/services/book?wsdlFor more information on the XFire plug-in refer the documentation on the wiki.
13.3 RSS and AtomNo direct support is provided for RSS or Atom within Grails. You could construct RSS or ATOM feeds with the render method's XML capability. There is however a Feeds plug-in available for Grails that provides a RSS and Atom builder using the popular ROME library. An example of its usage can be seen below:
def feed = { render(feedType:"rss", feedVersion:"2.0") { title = "My test feed" link = "http://your.test.server/yourController/feed" Article.list().each() { entry(it.title) { link = "http://your.test.server/article/${it.id}" it.content // return the content } } } }
14. Grails and SpringThis section is for advanced users and those who are interested in how Grails integrates with and builds on the Spring Framework This section is also useful for plug-in developers considering doing runtime configuration Grails.
14.1 The Underpinnings of GrailsGrails is actually a Spring MVC application in disguise. Spring MVC is the Spring framework's built-in MVC web application framework. Although Spring MVC suffers from the same difficulties as frameworks like Struts in terms of its ease of use, it is superbly designed and architected and was, for Grails, the perfect framework to build another framework on top of.Grails leverages Spring MVC in the following areas:
- Basic controller logic - Grails subclasses Spring's DispatcherServlet and uses it to delegate onto Grails controllers
- Data Binding and Validation - Grails' validation and data binding capabilities are built on those provided by Spring
- Runtime configuration - Grails' entire runtime convention based system is wired together by a Spring ApplicationContext
- Transactions - Grails uses Spring's transaction management in GORM
The Grails ApplicationContextSpring developers are often keen to understand how the Grails
ApplicationContext instance is constructed. The basics of it are as follows.
- Grails constructs a parent
ApplicationContextfrom the
web-app/WEB-INF/applicationContext.xml. This
ApplicationContextsets up the GrailsApplication instance and the GrailsPluginManager.
- Using this
ApplicationContextas a parent Grails' analyses the conventions with the
GrailsApplicationinstance and constructs a child
ApplicationContextthat is used as the root
ApplicationContextof the web application
Configured Spring BeansMost of Grails' configuration happens at runtime. Each plug-in may configure Spring beans that are registered with the
ApplicationContext. For a reference as to which beans are configured refer to the reference guide which describes each of the Grails plug-ins and which beans they configure.
14.2 Configuring Additional Beans
Using XMLBeans can be configured using the
grails-app/conf/spring/resources.xml file of your Grails application. This file is typical Spring XML file and the Spring documentation has an excellent reference on how to go about configuration Spring beans. As a trivial example you can configure a bean with the following syntax:
Once configured the bean, in this case named
<bean id="myBean" class="my.company.MyBeanImpl"></bean>
myBean, can be auto-wired into most Grails types including controllers, tag libraries, services and so on:
class ExampleController { def myBean }
Referencing Existing BeansBeans declared in
resources.xml can also reference Grails classes by convention. For example if you need a reference to a service such as
BookService in your bean you use the property name representation of the class name. In the case of
BookService this would be
bookService. For example:
The bean itself would of course need a public setter, which in Groovy is defined like this:
<bean id="myBean" class="my.company.MyBeanImpl"> <property name="bookService" ref="bookService" /> </bean>
or in Java like this:
package my.company
class MyBeanImpl {
BookService bookService
Since much of Grails configuration is done at runtime by convention many of the beans are not declared anywhere, but can still be referenced inside your Spring configuration. For example if you need a reference to the Grails
package my.company; class MyBeanImpl { private BookService bookService; public void setBookService(BookService theBookService) { this.bookService = theBookService; } }
DataSource you could do:
Or if you need the Hibernate
<bean id="myBean" class="my.company.MyBeanImpl"> <property name="bookService" ref="bookService" /> <property name="dataSource" ref="dataSource" /> </bean>
SessionFactory this will work:
For a full reference of the available beans see the Plug-in reference in the reference guide.
<bean id="myBean" class="my.company.MyBeanImpl"> <property name="bookService" ref="bookService" /> <property name="sessionFactory" ref="sessionFactory" /> </bean>
Using the Spring DSLIf you want to use the Spring DSL that Grails provides then you need to create a
grails-app/conf/spring/resources.groovy file and define a property called
beans that is assigned a block:
The same configuration for the XML example could be represented as:
beans = { // beans here }
The main advantage of this way is that you can now mix logic in within your bean definitions, for example based on the environment:
beans = {
myBean(my.company.MyBeanImpl) {
bookService = ref("bookService")
import grails.util.* beans = { switch(Environment.current) { case Environment.PRODUCTION: myBean(my.company.MyBeanImpl) { bookService = ref("bookService") } break case Environment.DEVELOPMENT: myBean(my.company.mock.MockImpl) { bookService = ref("bookService") } break } }
GrailsApplication object can be accessed by the
application variable, which can be used to access config (amongst other things):
import grails.util.* beans = { if (application.config.my.company.mockService) { myBean(my.company.mock.MockImpl) { bookService = ref("bookService") } } else { myBean(my.company.MyBeanImpl) { bookService = ref("bookService") } } }
14.3 Runtime Spring with the Beans DSLThis Bean builder in Grails aims to provide a simplified way of wiring together dependencies that uses Spring at its core. In addition, Spring's regular way of configuration (via XML) is essentially static and very difficult to modify and configure at runtime other than programmatic XML creation which is both error prone and verbose. Grails' BeanBuilder changes all that by making it possible to programmatically wire together components at runtime thus allowing you to adapt the logic based on system properties or environment variables. This enables the code to adapt to its environment and avoids unnecessary duplication of code (having different Spring configs for test, development and production environments)
The BeanBuilder classGrails provides a grails.spring.BeanBuilder class that uses dynamic Groovy to construct bean definitions. The basics are as follows:
import org.apache.commons.dbcp.BasicDataSource import org.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean; import org.springframework.context.ApplicationContext;def bb = new grails.spring.BeanBuilder()bb.beans { dataSource(BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = dataSource hibernateProperties = [ "hibernate.hbm2ddl.auto":"create-drop", "hibernate.show_sql":true ] } }ApplicationContext appContext = bb.createApplicationContext()
Within plug-ins and the grails-app/conf/spring/resources.groovy file you don't need to create a new instance ofThe above example shows how you would configure Hibernate with an appropriate data source with the
BeanBuilder. Instead the DSL is implicitly available inside the
beansblocks respectively.
BeanBuilder class.Essentially, each method call (in this case
dataSource and
sessionFactory calls) map to the name of the bean in Spring. The first argument to the method is the bean's class, whilst the last argument is a block. Within the body of the block you can set properties on the bean using standard Groovy syntaxBean references are resolved automatically be using the name of the bean. This can be seen in the example above with the way the
sessionFactory bean resolves the
dataSource reference.Certain special properties related to bean management can also be set by the builder, as seen in the following code:
The strings in square brackets are the names of the equivalent bean attributes in Spring's XML definition.
sessionFactory(ConfigurableLocalSessionFactoryBean) { bean -> bean.autowire = 'byName' // Autowiring behaviour. The other option is 'byType'. [autowire] bean.initMethod = 'init' // Sets the initialisation method to 'init'. [init-method] bean.destroyMethod = 'destroy' // Sets the destruction method to 'destroy'. [destroy-method] bean.scope = 'request' // Sets the scope of the bean. [scope] dataSource = dataSource hibernateProperties = [ "hibernate.hbm2ddl.auto":"create-drop", "hibernate.show_sql":true ] }
Using BeanBuilder with Spring MVCIf you want to take advantage of BeanBuilder in a regular Spring MVC application you need to make sure the
grails-spring-<version>.jar file is in your classpath. Once that is done you can need to set the following
<context-param> values in your
/WEB-INF/web.xml file:
With that done you can then create a /WEB-INF/applicationContext.groovy file that does the rest:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.groovy</param-value> </context-param> <context-param> <param-name>contextClass</param-name> <param-value>org.codehaus.groovy.grails.commons.spring.GrailsWebApplicationContext</param-value> </context-param>
beans { dataSource(org.apache.commons.dbcp.BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" } }
Loading Bean Definitions from the File SystemYou can use the
BeanBuilder class to load external Groovy scripts that define beans using the same path matching syntax defined here. Example:
Here the
def bb = new BeanBuilder() bb.loadBeans("classpath:*SpringBeans.groovy")def applicationContext = bb.createApplicationContext()
BeanBuilder will load all Groovy files on the classpath ending with
SpringBeans.groovy and parse them into bean definitions. An example script can be seen below:
beans { dataSource(BasicDataSource) { driverClassName = "org.hsqldb.jdbcDriver" url = "jdbc:hsqldb:mem:grailsDB" username = "sa" password = "" } sessionFactory(ConfigurableLocalSessionFactoryBean) { dataSource = dataSource hibernateProperties = [ "hibernate.hbm2ddl.auto":"create-drop", "hibernate.show_sql":true ] } }
Adding Variables to the Binding (Context)If you're loading beans from a script you can set the binding to use by creating a Groovy Binding object:
def binding = new Binding() binding.foo = "bar"def bb = new BeanBuilder() bb.binding = binding bb.loadBeans("classpath:*SpringBeans.groovy")def ctx = bb.createApplicationContext()
14.4 The BeanBuilder DSL Explained
Using Constructor ArgumentsConstructor arguments can be defined using parameters to each method that reside between the class of the bean and the last closure:
bb.beans {
exampleBean(MyExampleBean, "firstArgument", 2) {
someProperty = [1,2,3]
Configuring the BeanDefinition (Using factory methods)The first argument to the closure is a reference to the bean configuration instance, which you can use to configure factory methods and invoke any method on the AbstractBeanDefinition class:
As an alternative you can also use the return value of the bean defining method to configure the bean:
bb.beans { exampleBean(MyExampleBean) { bean -> bean.factoryMethod = "getInstance" bean.singleton = false someProperty = [1,2,3] } }
bb.beans {
def example = exampleBean(MyExampleBean) {
someProperty = [1,2,3]
example.factoryMethod = "getInstance"
Using Factory beansSpring defines the concept of factory beans and often a bean is created not from a class, but from one of these factories. In this case the bean has no class and instead you must pass the name of the factory bean to the bean:
Note in the example above instead of a class we pass a reference to the
bb.beans {
myFactory(ExampleFactoryBean) {
someProperty = [1,2,3]
myBean(myFactory) {
name = "blah"
myFactory bean into the bean defining method. Another common task is provide the name of the factory method to call on the factory bean. This can be done using Groovy's named parameter syntax:
Here the
bb.beans { myFactory(ExampleFactoryBean) { someProperty = [1,2,3] } myBean(myFactory:"getInstance") { name = "blah" } }
getInstance method on the
ExampleFactoryBean bean will be called in order to create the
myBean bean.
Creating Bean References at RuntimeSometimes you don't know the name of the bean to be created until runtime. In this case you can use a string interpolation to invoke a bean defining method dynamically:
In this case the
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1,2,3] } }
beanName variable defined earlier is used when invoking a bean defining method.Furthermore, because sometimes bean names are not known until runtime you may need to reference them by name when wiring together other beans. In this case using the
ref method:
Here the example property of
def beanName = "example" bb.beans { "${beanName}Bean"(MyExampleBean) { someProperty = [1,2,3] } anotherBean(AnotherBean) { example = ref("${beanName}Bean") } }
AnotherBean is set using a runtime reference to the
exampleBean. The
ref method can also be used to refer to beans from a parent
ApplicationContext that is provided in the constructor of the
Here the second parameter
ApplicationContext parent = ...// der bb = new BeanBuilder(parent) bb.beans { anotherBean(AnotherBean) { example = ref("${beanName}Bean", true) } }
true specifies that the reference will look for the bean in the parent context.
Using Anonymous (Inner) BeansYou can use anonymous inner beans by setting a property of the bean to a block that takes an argument that is the bean type:
In the above example we set the
bb.beans { marge(Person.class) { name = "marge" husband = { Person p -> name = "homer" age = 45 props = [overweight:true, height:"1.8m"] } children = [bart, lisa] } bart(Person) { name = "Bart" age = 11 } lisa(Person) { name = "Lisa" age = 9 } }
marge bean's husband property to a block that creates an inner bean reference. Alternatively if you have a factory bean you can ommit the type and just use passed bean definition instead to setup the factory:
bb.beans { personFactory(PersonFactory.class) marge(Person.class) { name = "marge" husband = { bean -> bean.factoryBean = "personFactory" bean.factoryMethod = "newInstance" name = "homer" age = 45 props = [overweight:true, height:"1.8m"] } children = [bart, lisa] } }
Abstract Beans and Parent Bean DefinitionsTo create an abstract bean definition define a bean that takes no class:
Here we define an abstract bean that sets that has a
class HolyGrailQuest { def start() { println "lets begin" } } class KnightOfTheRoundTable { String name String leader KnightOfTheRoundTable(String n) { this.name = n } HolyGrailQuest quest def embarkOnQuest() { quest.start() } }def bb = new grails.spring.BeanBuilder() bb.beans { abstractBean { leader = "Lancelot" } … }
leader property with the value of
"Lancelot". Now to use the abstract bean set it as the parent of the child bean:
bb.beans {
knights(KnightOfTheRoundTable, "Camelot") { bean ->
bean.parent = abstractBean
quest = quest
When using a parent bean you must set the parent property of the bean before setting any other properties on the bean!If you want an abstract bean that has a class you can do it this way:
In the above example we create an abstract bean of type
def bb = new grails.spring.BeanBuilder() bb.beans { abstractBean(KnightOfTheRoundTable) { bean -> bean.'abstract' = true leader = "Lancelot" } quest(HolyGrailQuest) knights("Camelot") { bean -> bean.parent = abstractBean quest = quest } }
KnightOfTheRoundTable and use the bean argument to set it to abstract. Later we define a knights bean that has no class, but inherits the class from the parent bean.
Using Spring NamespacesSince Spring 2.0, users of Spring have been granted easier access to key features via XML namespaces. With BeanBuilder you can use any Spring namespace by first declaring it:
And then invoking a method that matches the names of the Spring namespace tag and its associated attributes:
xmlns context:"http://www.springframework.org/schema/context"
You can do some useful things with Spring namespaces, such as looking up a JNDI resource:
context.'component-scan'( 'base-package' :"my.company.domain" )
The example above will create a Spring bean with the identifier of
xmlns jee:"http://www.springframework.org/schema/jee"jee.'jndi-lookup'(id:"dataSource", 'jndi-name':"java:comp/env/myDataSource")
dataSource by performing a JNDI lookup on the given JNDI name. With Spring namespaces you also get full access to all of the powerful AOP support in Spring from BeanBuilder. For example given the following two classes:
You can define an AOP aspect that uses a pointcut to detect whenever the
class Person { int age; String name; void birthday() { ++age; } } class BirthdayCardSender { List peopleSentCards = [] void onBirthday(Person person) { peopleSentCards << person } }
birthday() method is called:
xmlns aop:"http://www.springframework.org/schema/aop" fred(Person) { name = "Fred" age = 45 }birthdayCardSenderAspect(BirthdayCardSender)aop { config("proxy-target-class":true) { aspect( id:"sendBirthdayCard",ref:"birthdayCardSenderAspect" ) { after method:"onBirthday", pointcut: "execution(void ..Person.birthday()) and this(person)" } } }
14.5 Property Placeholder ConfigurationGrails supports the notion of property placeholder configuration through an extended version of Spring's PropertyPlaceholderConfigurer, which is typically useful when used in combination with externalized configuration.Settings defined in either ConfigSlurper scripts of Java properties files can be used as placeholder values for Spring configuration in
grails-app/conf/spring/resources.xml. For example given the following entries in
grails-app/conf/Config.groovy (or an externalized config):
You can then specify placeholders in
database.driver="com.mysql.jdbc.Driver" database.dbname="mysql:mydb"
resources.xml as follows using the familiar ${..} syntax:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"><value>${database.driver}</value></property> <property name="url"><value>jdbc:${database.dbname}</value></property> </bean>
14.6 Property Override ConfigurationGrails supports setting of bean properties via configuration. This is often useful when used in combination with externalized configuration.Essentially you define a
beans block with the names of beans and their values:
The general format is:
beans {
bookService {
webServiceURL = "http://www.amazon.com"
The same configuration in a Java properties file would be:
[bean name].[property name] = [value]
15. Grails and HibernateIf GORM (Grails Object Relational Mapping) is not flexible enough for your liking you can alternatively map your domain classes using Hibernate, either via XML mapping files or JPA annotations. You will be able to map Grails domain classes onto a wider range of legacy systems and be more flexible in the creation of your database schema. Best of all, you will still be able to call all of the dynamic persistent and query methods provided by GORM!
15.1 Using Hibernate XML Mapping FilesMapping your domain classes via XML is pretty straightforward. Simply create a
hibernate.cfg.xml file in your project's
grails-app/conf/hibernate directory, either manually or via the create-hibernate-cfg-xml command, that contains the following:
The individual mapping files, like 'org.example.Book.hbm.xml' in the above example, also go into the
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Example mapping file inclusion --> <mapping resource="org.example.Book.hbm.xml"/> … </session-factory> </hibernate-configuration>
grails-app/conf/hibernate directory. To find out how to map domain classes via XML, check out the Hibernate manual.If the default location of the
hibernate.cfg.xml file doesn't suit you, you can change it by specifying an alternative location in
or even a list of locations:
hibernate {
config.location = "file:/path/to/my/hibernate.cfg.xml"
Grails also allows you to write your domain model in Java or re-use an existing one that already has Hibernate mapping files. Simply place the mapping files into
hibernate { config.location = ["file:/path/to/one/hibernate.cfg.xml","file:/path/to/two/hibernate.cfg.xml"] }
grails-app/conf/hibernate and either put the Java files in
src/java or (if the domain model is stored in a JAR) the packaged classes into the project's
lib directory. You still need the
hibernate.cfg.xml though!
15.2 Mapping with Hibernate AnnotationsTo map a domain class via annotations, create a new class in
src/java and use the annotations defined as part of the EJB 3.0 spec (for more info on this see the Hibernate Annotations Docs):
Once that is done you need to register the class with the Hibernate
package com.books; @Entity public class Book { private Long id; private String title; private String description; private Date date; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
sessionFactory by adding relevant entries to the
grails-app/conf/hibernate/hibernate.cfg.xml file as follows:
See the previous section for more information on the
<!DOCTYPE hibernate-configuration SYSTEM "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <mapping package="com.books" /> <mapping class="com.books.Book" /> </session-factory> </hibernate-configuration>
hibernate.cfg.xml file.When Grails loads it will register the necessary dynamic methods with the class. To see what else you can do with a Hibernate domain class see the section on Scaffolding.
15.3 Adding ConstraintsEven if you use a Java domain model, you can still take advantage of GORM validation. Grails allows you to define constraints through a separate script that you place in the
src/java directory. The script should be in a directory that matches the package of the corresponding domain class and its name should have a Constraints suffix. For example, if you had a domain class
org.example.Book, then you would create the script
src/java/org/example/BookConstraints.groovy.The contents of the script should contain a standard GORM constraints block like so:
Once the script is in place, you'll be able to validate instances of your domain class!
constraints = { title(blank: false) author(blank: false) }
15.4 Further ReadingGrails committer, Jason Rudolph, took the time to write many useful articles about using Grails with custom Hibernate mappings including:
- Hoisting Grails to Your Legacy DB - An excellent article about using Grails with Hibernate XML
- Grails + EJB3 Domain Models - Another great article about using Grails with EJB3-style annotated domain models
16. ScaffoldingScaffolding allows you to auto-generate a whole application for a given domain class including:
- The necessary views
- Controller actions for create/read/update/delete (CRUD) operations
Enabling ScaffoldingThe simplest way to get started with scaffolding is to enable scaffolding via the
scaffold property. For the
Book domain class, you need to set the
scaffold property on a controller to true:
The above works because the
class BookController { static scaffold = true }
BookController follows the same naming convention as the
Book domain class. If we wanted to scaffold a specific domain class we could reference the class directly in the scaffold property:
With that done if you run this grails application the necessary actions and views will be auto-generated at runtime. The following actions are dynamically implemented by default by the runtime scaffolding mechanism:
class SomeController {
static scaffold = Author
- list
- show
- edit
- delete
- create
- save
- update
http://localhost:8080/app/bookIf you prefer to keep your domain model in Java and mapped with Hibernate you can still use scaffolding, simply import the necessary class and set the scaffold property to it.
Dynamic ScaffoldingNote that when using the scaffold property Grails does not use code templates, or code generation to achieve this so you can add your own actions to the scaffolded controller that interact with the scaffolded actions. For example, in the below example,
changeAuthor redirects to the
show action which doesn't actually exist physically:
You can also override the scaffolded actions with your own actions if necessary:
class BookController { static scaffold = Book def changeAuthor = { def b = Book.get( params["id"] ) b.author = Author.get( params["author.id"] ) b.save() // redirect to a scaffolded action redirect(action:show) } }
All of this is what is known as "dynamic scaffolding" where the CRUD interface is generated dynamically at runtime. Grails also supports "static" scaffolding which will be discussed in the following sections.
class BookController { static scaffold = Book // overrides scaffolded action to return both authors and books def list = { [ bookInstanceList : Book.list(), bookInstanceTotal: Book.count(), authorInstanceList: Author.list() ] } def show = { def book = Book.get(params.id) log.error(book) [ bookInstance : book ] }}
By default, the size of text areas in scaffolded views is defined in the CSS, so adding 'rows' and 'cols' attributes will have no effect.Also, the standard scaffold views expect model variables of the form
<propertyName>InstanceListfor collections and
<propertyName>Instancefor single instances. It's tempting to use properties like 'books' and 'book', but those won't work.
Customizing the Generated ViewsThe views that Grails generates have some form of intelligence in that they adapt to the Validation constraints. For example you can change the order that fields appear in the views simply by re-ordering the constraints in the builder:
You can also get the generator to generate lists instead of text inputs if you use the
def constraints = { title() releaseDate() }
inList constraint:
Or if you use the
def constraints = { title() category(inList:["Fiction", "Non-fiction", "Biography"]) releaseDate() }
range constraint on a number:
Restricting the size via a constraint also effects how many characters can be entered in the generated view:
def constraints = { age(range:18..65) }
def constraints = { name(size:0..30) }
Generating Controllers & ViewsThe above scaffolding features are useful but in real world situations its likely that you will want to customize the logic and views. Grails allows you to generate a controller and the views used to create the above interface via the command line. To generate a controller type:
Or to generate the views type:
grails generate-controller Book
Or to generate everything type:
grails generate-views Book
If you have a domain class in a package or are generating from a Hibernate mapped class remember to include the fully qualified package name:
grails generate-all Book
grails generate-all com.bookstore.Book
Customizing the Scaffolding templatesThe templates used by Grails to generate the controller and views can be customized by installing the templates with the install-templates command.
17. DeploymentGrails applications can be deployed in a number of ways, each of which has its pros and cons.
"grails run-app"You should be very familiar with this approach by now, since it is the most common method of running an application during the development phase. An embedded Tomcat server is launched that loads the web application from the development sources, thus allowing it to pick up an changes to application files.This approach is not recommended at all for production deployment because the performance is poor. Checking for and loading changes places a sizable overhead on the server. Having said that,
grails prod run-app removes the per-request overhead and allows you to fine tune how frequently the regular check takes place.Setting the system property "disable.auto.recompile" to
true disables this regular check completely, while the property "recompile.frequency" controls the frequency. This latter property should be set to the number of seconds you want between each check. The default is currently 3.
"grails run-war"This is very similar to the previous option, but Tomcat runs against the packaged WAR file rather than the development sources. Hot-reloading is disabled, so you get good performance without the hassle of having to deploy the WAR file elsewhere.
WAR fileWhen it comes down to it, current java infrastructures almost mandate that web applications are deployed as WAR files, so this is by far the most common approach to Grails application deployment in production. Creating a WAR file is as simple as executing the war command:
There are also many ways in which you can customise the WAR file that is created. For example, you can specify a path (either absolute or relative) to the command that instructs it where to place the file and what name to give it:
grails war
Alternatively, you can add a line to
grails war /opt/java/tomcat-5.5.24/foobar.war
grails-app/conf/BuildConfig.groovy that changes the default location and filename:
Of course, any command line argument that you provide overrides this setting.It is also possible to control what libraries are included in the WAR file, in case you need to avoid conflicts with libraries in a shared folder for example. The default behavior is to include in the WAR file all libraries required by Grails, plus any libraries contained in plugin "lib" directories, plus any libraries contained in the application's "lib" directory. As an alternative to the default behavior you can explicitly specify the complete list of libraries to include in the WAR file by setting the property
grails.project.war.file = "foobar-prod.war"
grails.war.dependencies in BuildConfig.groovy to either lists of Ant include patterns or closures containing AntBuilder syntax. Closures are invoked from within an Ant "copy" step, so only elements like "fileset" can be included, whereas each item in a pattern list is included. Any closure or pattern assigned to the latter property will be included in addition to
grails.war.dependencies only if you are running JDK 1.5 or above.Be careful with these properties: if any of the libraries Grails depends on are missing, the application will almost certainly fail. Here is an example that includes a small subset of the standard Grails dependencies:
This example only exists to demonstrate the syntax for the properties. If you attempt to use it as is in your own application, the application will probably not work. You can find a list of dependencies required by Grails in the "dependencies.txt" file that resides in the root directory of the unpacked distribution. You can also find a list of the default dependencies included in WAR generation in the "War.groovy" script - see the "DEFAULT_DEPS" and "DEFAULT_J5_DEPS" variables.The remaining two configuration options available to you are
def deps = [ "hibernate3.jar", "groovy-all-*.jar", "standard-${servletVersion}.jar", "jstl-${servletVersion}.jar", "oscache-*.jar", "commons-logging-*.jar", "sitemesh-*.jar", "spring-*.jar", "log4j-*.jar", "ognl-*.jar", "commons-*.jar", "xstream-1.2.1.jar", "xpp3_min-220.127.116.11.O.jar" ]grails.war.dependencies = { fileset(dir: "libs") { deps.each { pattern -> include(name: pattern) } } }
grails.war.copyToWebApp and
grails.war.resources. The first of these allows you to customise what files are included in the WAR file from the "web-app" directory. The second allows you to do any extra processing you want before the WAR file is finally created.
// This closure is passed the command line arguments used to start the // war process. grails.war.copyToWebApp = { args -> fileset(dir:"web-app") { include(name: "js/**") include(name: "css/**") include(name: "WEB-INF/**") } }// This closure is passed the location of the staging directory that // is zipped up to make the WAR file, and the command line arguments. // Here we override the standard web.xml with our own. grails.war.resources = { stagingDir, args -> copy(file: "grails-app/conf/custom-web.xml", tofile: "${stagingDir}/WEB-INF/web.xml") }