A 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.

This is one of the ways that Grails unifies access to the different scopes.

Using Flash Scope

Grails 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:

Returning the Model

A 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, the first way is to explicitly return a map instance:

def show = {
[ book : Book.get( params.id ) ]
}

If no explicit model is returned the controller's properties will be used as the model thus allowing you to write code like this:

In this case Grails will attempt to render a view at the location 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:

// 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
redirect(uri:"/login.html")

Or a full URL:

// Redirect to a URL
redirect(url:"http://grails.org")

Parameters can be optionally passed from one action to the next using the params argument of the method:

redirect(action:myaction, params:[myparam:"myvalue"])

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 params object is also a map, you can use it to pass the current request parameters from one action to the next:

redirect(action:"next", params:params)

Finally, you can also include a fragment in the target URI:

redirect(controller: "test", action: "show", fragment: "profile")

will (depending on the URL mappings) redirect to something like "/myapp/test/show#profile".

h4. Chaining

Actions 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:

Often 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 Interception

The 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:

def beforeInterceptor = {
println "Tracing action ${actionUri}"
}

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:

The above code defines a method called 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 Interception

To define an interceptor that is executed after an action use the afterInterceptor property:

This allows the view to be changed based on the model returned by the current action. Note that the modelAndView may be null if the action being intercepted called redirect or render.

Interception Conditions

Rails 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):

def beforeInterceptor = [action:this.&auth,except:'login']

This executes the interceptor for all actions except the specified action. A list of actions can also be defined as follows:

Data 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.

Binding Request Data to the Model

There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' implicit constructor:

def save = {
def b = new Book(params)
b.save()
}

The data binding happens within the code 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:

/book/save?title=The%20Stand&author=Stephen%20King

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:

Data binding and Single-ended Associations

If 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:

/book/save?author.id=20

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:

def b = new Book(params)

Data Binding and Many-ended Associations

If 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 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 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 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.

Data binding with Multiple domain classes

It is possible to bind data to multiple domain objects from the params object.

For example so you have an incoming request to:

/book/save?book.title=The%20Stand&author.name=Stephen%20King

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.

def b = new Book(params['book'])

Notice how we use the prefix before the first dot of the 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 errors

Sometimes 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:

class Book {
…
URL publisherURL
}

Here we have a domain class Book that uses the Java concrete type java.net.URL to represent URLs. Now say we had an incoming request such as:

/book/save?publisherURL=a-bad-url

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:

def b = new Book(params)

if(b.hasErrors()) {
println "The value ${b.errors.getFieldError('publisherURL').rejectedValue} is not a valid URL!"
}

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:

typeMismatch.java.net.URL=The field {0} is not a valid URL

Or a more specific one:

typeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL

Data Binding and Security concerns

When 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:

def p = Person.get(1)

p.properties['firstName','lastName'] = params

In this case only the 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:

def p = new Person()
bindData(p, params)

However, the bindData method also allows you to exclude certain parameters that you don't want updated:

The 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 versions

JSONBuilder 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 JSONBuilder

For 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 Config.groovy:

grails.json.legacy.builder=false

Rendering Simple Objects

To render a simple JSON object just set properties within the context of the closure:

Grails 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 Objects

Command objects are typically declared in the same source file as a controller directly below the controller class definition. For example:

Using Command Objects

To 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:

Grails 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:

<g:form useToken="true" ...>

Then in your controller code you can use the withForm method to handle valid and invalid requests:

withForm {
// good request
}.invalidToken {
// bad request
}

If you only provide the withForm method and not the chained 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:

Type Conversion Methods

If 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:

def total = params.int('total')

The above example uses the int method, there are also methods for boolean, long, char, 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 tagLibraries parameter of GSP tags.

Handling Multi Parameters

A 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:

Groovy 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:

render(view:"index")

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:

def show = {
[book: Book.get(params.id)]
}

This action will look-up a 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 book:

In 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 ${expr}:

<html><body>
Hello ${params.name}
</body></html>

However, unlike JSP EL you can have any Groovy expression within the ${..} 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 grails-app/conf/Config.groovy:

grails.views.default.codec='html'

Other possible values are 'none' (for no default encoding) and 'base64'.

Now 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:

<g:example />

GSP tags can also have a body such as:

<g:example>
Hello world
</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 attr="${new Date()}">
Hello world
</g:example>

Maps can also be passed into GSP tag attributes, which are often used for a named parameter style syntax:

The above example is also interesting due to its usage of GPath. GPath is Groovy's equivalent to an XPath like language. Essentially the 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!

GSP 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:

Form Basics

GSP 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:

Multiple Submit Buttons

The 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:

One 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 GSPs

When 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:

Static Resource: ${createLinkTo(dir:"images", file:"logo.jpg")}

This is particularly useful when you need to use a tag within an attribute:

<img src="${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="<g:createLinkTo dir="images" file="logo.jpg" />" />

Tags as method calls from Controllers and Tag Libraries

You 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:

As 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 Basics

Grails 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 grails-app/views/book/_bookTemplate.gsp:

Shared Templates

In 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:

<g:render template="/shared/mySharedTemplate" />

You can also use this technique to reference templates in any directory from any view or controller:

<g:render template="/book/bookTemplate" model="[book:myBook]" />

The Template Namespace

Since templates are used so frequently there is template namespace, called tmpl, available that makes using templates easier. Consider for example the following usage pattern:

<g:render template="bookTemplate" model="[book:myBook]" />

This can be expressed with the tmpl namespace as follows:

<tmpl:bookTemplate book="${myBook}" />

Templates in Controllers and Tag Libraries

You can also render templates from controllers using the render method found within controllers, which is useful for Ajax applications:

Specifying A Layout In A Controller

Another 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:

class BookController {
static layout = 'customer'

def list = { … }
}

You can create a layout called 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:

class BookController {
static layout = 'custom/customer'

def list = { … }
}

Views rendered from that controller would be decorated with the grails-app/views/layouts/custom/customer.gsp template.

Layout by Convention

Another way to associate layouts is to use "layout by convention". For example, if you have a controller such as:

class BookController {
def list = { … }
}

You can create a layout called 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.

Inline Layouts

Grails' 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.

Although 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:

One 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.

The trailing slash on the grails.gsp.view.dir value is important! Without it, Grails will look for views in the parent directory.

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:

The key point here is that you must retain the view directory structure, including the 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.

As demonstrated above there is an implicit 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:

By 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:

class SimpleTagLib {
static namespace = "my"

def example = { attrs ->
…
}
}

Here we have specified a namespace of my and hence the tags in this tag lib must then be referenced from GSP pages like this:

<my:example name="..." />

Where the prefix is the same as the value of the static 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:

Throughout 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 grails-app/conf/UrlMappings.groovy.

The UrlMappings class contains a single property called mappings that has been assigned a block of code:

To 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:

"/product"(controller:"product", action:"list")

In this case we've mapped the URL /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:

"/product"(controller:"product")

An alternative syntax is to assign the controller and action to use within a block passed to the method:

"/product" {
controller = "product"
action = "list"
}

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:

"/hello"(uri:"/hello.dispatch")

Rewriting specific URIs is often useful when integrating with other frameworks.

Simple Variables

The 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:

static mappings = {
"/product/$id"(controller:"product")
}

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 id. For example given the URL /product/MacBook, the following code will render "MacBook" to the response:

class ProductController {
def index = { render params.id }
}

You can of course construct more complex examples of mappings. For example the traditional blog URL format could be mapped as follows:

The individual tokens in the URL would again be mapped into the params object with values available for year, month, day, id and so on.

Dynamic Controller and Action Names

Variables can also be used to dynamically construct the controller and action name. In fact the default Grails URL mappings use this technique:

static mappings = {
"/$controller/$action?/$id?"()
}

Here the name of the controller, action and id are implicitly obtained from the variables controller, 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 Variables

Another 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:

If 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:

static mappings = {
"/"(view:"/index") // map the root URL
}

Alternatively if you need a view that is specific to a given controller you could use:

static mappings = {
"/help"(controller:"site",view:"help") // to a view for a controller
}

URL 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:

URL 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.

Overview

Grails 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.

Creating a Flow

To create a flow create a regular Grails controller and then add an action that ends with the convention Flow. For example:

As 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 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: grails-app/views/book/shoppingCart.

The 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.

View states

It will look for a view called 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:

Action States

An 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 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:

on(Exception).to "handleError"

What this does is make the flow transition to a state called 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 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 Actions

Another 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:

In 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 State

As 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 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 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 Action

To 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:

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:

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 Serialization

When placing objects in flash, 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:

class Book {
String title
}

In order to place an instance of the Book class in a flow scope you will need to modify it as follows:

class Book implements Serializable {
String title
}

This also impacts associations and closures you declare within a domain class. For example consider this:

class Book implements Serializable {
String title
Author author
}

Here if the Author association is not Serializable you will also get an error. This also impacts closures used in GORM events such as onLoad, onSave and so on. The following domain class will cause an error if an instance is placed in a flow scope:

In 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:

Notice how we perform data binding from request parameters and place the 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:

Notice how it places the 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:

Although 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.

To 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:

class ExampleFilters {
def filters = {
// your filters here
}
}

Each filter you define within the 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:

Here the 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.

Ajax 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.

Remote 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:

<g:remoteLink action="delete" id="1">Delete Book</g:remoteLink>

The above link sends an asynchronous request to the delete action of the current controller with an id of 1.

The above example will call the action and set the contents of the messagediv 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:

Although 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

Most of the examples in the Ajax section cover Content Centric Ajax where you are updating the page, but you may also want to use Data Centric or Script Centric. This guide covers the different styles of Ajax.

Content Centric Ajax

Just 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:

The important thing to remember is to set the 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.

Grails 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 Types

Before 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.

Content Negotiation using the Accept header

Every 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):

What happens here is that if the preferred format is 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 Parameter

If fiddling with request headers if not your favorite activity you can override the format used by specifying a format request parameter:

Content Negotiation with URI Extensions

Grails also supports content negotiation via URI extensions. For example given the following URI:

/book/list.xml

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 false:

grails.mime.file.extensions = false

Testing Content Negotiation

To test content negotiation in an integration test (see the section on Testing) you can either manipulate the incoming request headers: