(Quick Reference)

8 The Web Layer

Version: 7.0.0-SNAPSHOT

Table of Contents

8 The Web Layer

8.1 Controllers

A controller handles requests and creates or prepares the response. A controller can generate the response directly or delegate to a view. To create a controller, simply create a class whose name ends with Controller in the grails-app/controllers directory (in a subdirectory if it’s in a package).

The default URL Mapping configuration ensures that the first part of your controller name is mapped to a URI and each action defined within your controller maps to URIs within the controller name URI.

8.1.1 Understanding Controllers and Actions

Creating a controller

Controllers can be created with the create-controller or generate-controller command. For example try running the following command from the root of a Grails project:

grails create-controller book

The command will create a controller at the location grails-app/controllers/myapp/BookController.groovy:

package myapp

class BookController {

    def index() { }
}

where "myapp" will be the name of your application, the default package name if one isn’t specified.

BookController by default maps to the /book URI (relative to your application root).

The create-controller and generate-controller commands are just for convenience and you can just as easily create controllers using your favorite text editor or IDE

Creating Actions

A controller can have multiple public action methods; each one maps to a URI:

class BookController {

    def list() {

        // do controller logic
        // create model

        return model
    }
}

This example maps to the /book/list URI by default thanks to the property being named list.

The Default Action

A controller has the concept of a default URI that maps to the root URI of the controller, for example /book for BookController. The action that is called when the default URI is requested is dictated by the following rules:

  • If there is only one action, it’s the default

  • If you have an action named index, it’s the default

  • Alternatively you can set it explicitly with the defaultAction property:

static defaultAction = "list"

8.1.2 Controllers and Scopes

Available Scopes

Scopes are hash-like objects where you can store variables. The following scopes are available to controllers:

  • servletContext - Also known as application scope, this scope lets you share state across the entire web application. The servletContext is an instance of 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 query string or POST parameters

  • flash - See below

Accessing Scopes

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

class BookController {
    def find() {
        def findBy = params["findBy"]
        def appContext = request["foo"]
        def loggedUser = session["logged_user"]
    }
}

You can also access values within scopes using the de-reference operator, making the syntax even more clear:

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.

Using Flash Scope

Grails supports the concept of flash scope as a temporary store to make attributes available for this request and the next request only. Afterwards the attributes are cleared. This is useful for setting a message directly before redirecting, 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
}

When the delete action is requested, the message value will be in scope and can be used to display an information message. It will be removed from the flash scope after this second request.

Note that the attribute name can be anything you want, and the values are often strings used to display messages, but can be any object type.

Scoped Controllers

Newly created applications have the grails.controllers.defaultScope property set to a value of "singleton" in application.yml. You may change this value to any of the supported scopes listed below. If the property is not assigned a value at all, controllers will default to "prototype" scope.

Supported controller scopes are:

  • prototype (default) - A new controller will be created for each request (recommended for actions as Closure properties)

  • session - One controller is created for the scope of a user session

  • singleton - Only one instance of the controller ever exists (recommended for actions as methods)

To enable one of the scopes, add a static scope property to your class with one of the valid scope values listed above, for example

static scope = "singleton"

You can define the default strategy in application.yml with the grails.controllers.defaultScope key, for example:

grails:
    controllers:
        defaultScope: singleton
Use scoped controllers wisely. For instance, we don’t recommend having any properties in a singleton-scoped controller since they will be shared for all requests.

8.1.3 Models and Views

Returning the Model

A model is a Map that the view uses when rendering. The keys within that Map correspond 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.

A more advanced approach is to return an instance of the Spring ModelAndView class:

import org.springframework.web.servlet.ModelAndView

def index() {
    // get some books just for the index page, perhaps your favorites
    def favoriteBooks = ...

    // forward to the list view to show them
    return new ModelAndView("/book/list", [ bookList : favoriteBooks ])
}

One thing to bear in mind is that certain variable names can not be used in your model:

  • attributes

  • application

Currently, no error will be reported if you do use them, but this will hopefully change in a future version of Grails.

Selecting the View

In both of the previous two examples there was no code that specified which view to render. So how does Grails know which one to pick? The answer lies in the conventions. Grails will look for a view at the location grails-app/views/book/show.gsp for this show action:

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

To render a different view, use the render method:

def show() {
    def map = [book: Book.get(params.id)]
    render(view: "display", model: map)
}

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 directory of the grails-app/views directory. This is convenient, but to access shared views, you use an absolute path instead of a relative one:

def show() {
    def map = [book: Book.get(params.id)]
    render(view: "/shared/display", model: map)
}

In this case Grails will attempt to render a view at the location grails-app/views/shared/display.gsp.

Grails also supports JSPs as views, so if a GSP isn’t found in the expected location but a JSP is, it will be used instead.

Unlike GSPs, JSPs must be located in the directory path /src/main/webapp/WEB-INF/grails-app/views.

Additionally, to ensure JSPs work as intended, don’t forget to include the required dependencies for JSP and JSTL implementations in your build.gradle file.

Selecting Views For Namespaced Controllers

If a controller defines a namespace for itself with the namespace property that will affect the root directory in which Grails will look for views which are specified with a relative path. The default root directory for views rendered by a namespaced controller is grails-app/views/<namespace name>/<controller name>/. If the view is not found in the namespaced directory then Grails will fallback to looking for the view in the non-namespaced directory.

See the example below.

class ReportingController {
    static namespace = 'business'

    def humanResources() {
        // This will render grails-app/views/business/reporting/humanResources.gsp
        // if it exists.

        // If grails-app/views/business/reporting/humanResources.gsp does not
        // exist the fallback will be grails-app/views/reporting/humanResources.gsp.

        // The namespaced GSP will take precedence over the non-namespaced GSP.

        [numberOfEmployees: 9]
    }


    def accountsReceivable() {
        // This will render grails-app/views/business/reporting/numberCrunch.gsp
        // if it exists.

        // If grails-app/views/business/reporting/numberCrunch.gsp does not
        // exist the fallback will be grails-app/views/reporting/numberCrunch.gsp.

        // The namespaced GSP will take precedence over the non-namespaced GSP.

        render view: 'numberCrunch', model: [numberOfEmployees: 13]
    }
}

Rendering a Response

Sometimes it’s easier (for example 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:

render "Hello World!"

The above code writes the text "Hello World!" to the response. Other examples include:

// 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")

If you plan on using Groovy’s MarkupBuilder to generate HTML for use with the render method be careful of naming clashes between HTML elements and Grails tags, for example:

import groovy.xml.MarkupBuilder
...
def login() {
    def writer = new StringWriter()
    def builder = new MarkupBuilder(writer)
    builder.html {
        head {
            title 'Log in'
        }
        body {
            h1 'Hello'
            form {
            }
        }
    }

    def html = writer.toString()
    render html
}

This will actually call the form tag (which will return some text that will be ignored by the MarkupBuilder). To correctly output a <form> element, use the following:

def login() {
    // ...
    body {
        h1 'Hello'
        builder.form {
        }
    }
    // ...
}

8.1.4 Redirects and Chaining

Redirects

Actions can be redirected using the redirect controller method:

class OverviewController {

    def login() {}

    def find() {
        if (!session.user)
            redirect(action: 'login')
            return
        }
        ...
    }
}

Internally the redirect method uses the HttpServletResponse object’s sendRedirect method.

The redirect method expects one of:

  • The name of an action (and controller name if the redirect isn’t to an action in the current controller):

// 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")
// Redirect to the domain instance
Book book = ... // obtain a domain instance
redirect book

In the above example Grails will construct a link using the domain class id (if present).

Parameters can optionally be 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 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 is used.

Since the params object is 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")

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

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 this action:

class ExampleChainController {

    def first() {
        chain(action: second, model: [one: 1])
    }

    def second () {
        chain(action: third, model: [two: 2])
    }

    def third() {
        [three: 3])
    }
}

results in the model:

[one: 1, two: 2, three: 3]

The model can be accessed in subsequent controller actions in the chain using the chainModel map. This dynamic property only exists in actions following the call to the chain method:

class ChainController {

    def nextInChain() {
        def model = chainModel.myModel
        ...
    }
}

Like the redirect method you can also pass parameters to the chain method:

chain(action: "action1", model: [one: 1], params: [myparam: "param1"])
The chain method uses the HTTP session and hence should only be used if your application is stateful.

8.1.5 Data Binding

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 by a form submission, are always strings whilst the properties of a Groovy or Java object may well not be.

Map Based Binding

The data binder is capable of converting and assigning values in a Map to properties of an object. The binder will associate entries in the Map to properties of the object using the keys in the Map that have values which correspond to property names on the object. The following code demonstrates the basics:

grails-app/domain/Person.groovy
class Person {
    String firstName
    String lastName
    Integer age
}
def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]

def person = new Person(bindingMap)

assert person.firstName == 'Peter'
assert person.lastName == 'Gabriel'
assert person.age == 63

To update properties of a domain object you may assign a Map to the properties property of the domain class:

def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63]

def person = Person.get(someId)
person.properties = bindingMap

assert person.firstName == 'Peter'
assert person.lastName == 'Gabriel'
assert person.age == 63

The binder can populate a full graph of objects using Maps of Maps.

class Person {
    String firstName
    String lastName
    Integer age
    Address homeAddress
}

class Address {
    String county
    String country
}
def bindingMap = [firstName: 'Peter', lastName: 'Gabriel', age: 63, homeAddress: [county: 'Surrey', country: 'England'] ]

def person = new Person(bindingMap)

assert person.firstName == 'Peter'
assert person.lastName == 'Gabriel'
assert person.age == 63
assert person.homeAddress.county == 'Surrey'
assert person.homeAddress.country == 'England'

Binding To Collections And Maps

The data binder can populate and update Collections and Maps. The following code shows a simple example of populating a List of objects in a domain class:

class Band {
    String name
    static hasMany = [albums: Album]
    List albums
}

class Album {
    String title
    Integer numberOfTracks
}
def bindingMap = [name: 'Genesis',
                  'albums[0]': [title: 'Foxtrot', numberOfTracks: 6],
                  'albums[1]': [title: 'Nursery Cryme', numberOfTracks: 7]]

def band = new Band(bindingMap)

assert band.name == 'Genesis'
assert band.albums.size() == 2
assert band.albums[0].title == 'Foxtrot'
assert band.albums[0].numberOfTracks == 6
assert band.albums[1].title == 'Nursery Cryme'
assert band.albums[1].numberOfTracks == 7

That code would work in the same way if albums were an array instead of a List.

Note that when binding to a Set the structure of the Map being bound to the Set is the same as that of a Map being bound to a List but since a Set is unordered, the indexes don’t necessarily correspond to the order of elements in the Set. In the code example above, if albums were a Set instead of a List, the bindingMap could look exactly the same but 'Foxtrot' might be the first album in the Set or it might be the second. When updating existing elements in a Set the Map being assigned to the Set must have id elements in it which represent the element in the Set being updated, as in the following example:

/*
 * The value of the indexes 0 and 1 in albums[0] and albums[1] are arbitrary
 * values that can be anything as long as they are unique within the Map.
 * They do not correspond to the order of elements in albums because albums
 * is a Set.
 */
def bindingMap = ['albums[0]': [id: 9, title: 'The Lamb Lies Down On Broadway']
                  'albums[1]': [id: 4, title: 'Selling England By The Pound']]

def band = Band.get(someBandId)

/*
 * This will find the Album in albums that has an id of 9 and will set its title
 * to 'The Lamb Lies Down On Broadway' and will find the Album in albums that has
 * an id of 4 and set its title to 'Selling England By The Pound'.  In both
 * cases if the Album cannot be found in albums then the album will be retrieved
 * from the database by id, the Album will be added to albums and will be updated
 * with the values described above.  If a Album with the specified id cannot be
 * found in the database, then a binding error will be created and associated
 * with the band object.  More on binding errors later.
 */
band.properties = bindingMap

When binding to a Map the structure of the binding Map is the same as the structure of a Map used for binding to a List or a Set and the index inside of square brackets corresponds to the key in the Map being bound to. See the following code:

class Album {
    String title
    static hasMany = [players: Player]
    Map players
}

class Player {
    String name
}
def bindingMap = [title: 'The Lamb Lies Down On Broadway',
                  'players[guitar]': [name: 'Steve Hackett'],
                  'players[vocals]': [name: 'Peter Gabriel'],
                  'players[keyboards]': [name: 'Tony Banks']]

def album = new Album(bindingMap)

assert album.title == 'The Lamb Lies Down On Broadway'
assert album.players.size() == 3
assert album.players.guitar.name == 'Steve Hackett'
assert album.players.vocals.name == 'Peter Gabriel'
assert album.players.keyboards.name == 'Tony Banks'

When updating an existing Map, if the key specified in the binding Map does not exist in the Map being bound to then a new value will be created and added to the Map with the specified key as in the following example:

def bindingMap = [title: 'The Lamb Lies Down On Broadway',
                  'players[guitar]': [name: 'Steve Hackett'],
                  'players[vocals]': [name: 'Peter Gabriel'],
                  'players[keyboards]': [name: 'Tony Banks']]

def album = new Album(bindingMap)

assert album.title == 'The Lamb Lies Down On Broadway'
assert album.players.size() == 3
assert album.players.guitar.name == 'Steve Hackett'
assert album.players.vocals.name  == 'Peter Gabriel'
assert album.players.keyboards.name  == 'Tony Banks'

def updatedBindingMap = ['players[drums]': [name: 'Phil Collins'],
                         'players[keyboards]': [name: 'Anthony George Banks']]

album.properties = updatedBindingMap

assert album.title == 'The Lamb Lies Down On Broadway'
assert album.players.size() == 4
assert album.players.guitar.name == 'Steve Hackett'
assert album.players.vocals.name == 'Peter Gabriel'
assert album.players.keyboards.name == 'Anthony George Banks'
assert album.players.drums.name == 'Phil Collins'

Binding Request Data to the Model

The params object that is available in a controller has special behavior that helps convert dotted request parameter names into nested Maps that the data binder can work with. For example, if a request includes request parameters named person.homeAddress.country and person.homeAddress.city with values 'USA' and 'St. Louis' respectively, params would include entries like these:

[person: [homeAddress: [country: 'USA', city: 'St. Louis']]]

There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map 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 be set on the domain class. You can use the properties property to perform data binding onto an existing instance:

def save() {
    def b = Book.get(params.id)
    b.properties = params
    b.save()
}

This has the same effect as using the implicit constructor.

When binding an empty String (a String with no characters in it, not even spaces), the data binder will convert the empty String to null. This simplifies the most common case where the intent is to treat an empty form field as having the value null since there isn’t a way to actually submit a null as a request parameter. When this behavior is not desirable the application may assign the value directly.

The mass property binding mechanism will by default automatically trim all Strings at binding time. To disable this behavior set the grails.databinding.trimStrings property to false in grails-app/conf/application.groovy.

// the default value is true
grails.databinding.trimStrings = false

// ...

The mass property binding mechanism will by default automatically convert all empty Strings to null at binding time. To disable this behavior set the grails.databinding.convertEmptyStringsToNull property to false in grails-app/conf/application.groovy.

// the default value is true
grails.databinding.convertEmptyStringsToNull = false

// ...

The order of events is that the String trimming happens and then null conversion happens so if trimStrings is true and convertEmptyStringsToNull is true, not only will empty Strings be converted to null but also blank Strings. A blank String is any String such that the trim() method returns an empty String.

These forms of data binding in Grails are very convenient, but also indiscriminate. In other words, they will bind all non-transient, typed instance properties of the target object, including ones that you may not want bound. Just because the form in your UI doesn’t submit all the properties, an attacker can still send malign data via a raw HTTP request. Fortunately, Grails also makes it easy to protect against such attacks - see the section titled "Data Binding and Security concerns" for more information.

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)

An association property can be set to null by passing the literal String "null". For example:

/book/save?author.id=null

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 (the default for a hasMany) then the simplest way to populate an association is to send a list of identifiers. For example consider the usage of <g:select> below:

<g:select name="books"
          from="${Book.list()}"
          size="5" multiple="yes" optionKey="id"
          value="${author?.books}" />

This produces a select box that lets you 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 use the subscript operator:

<g:textField name="books[0].title" value="the Stand" />
<g:textField name="books[1].title" value="the Shining" />

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 books[0] and books[1] 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 two and you refer to an element that is outside the size of association:

<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 a new instance for you at the defined position.

You can bind existing instances of the associated type to a List using the same .id syntax as you would use with a single-ended association. For example:

<g:select name="books[0].id" from="${bookList}"
          value="${author?.books[0]?.id}" />

<g:select name="books[1].id" from="${bookList}"
          value="${author?.books[1]?.id}" />

<g:select name="books[2].id" from="${bookList}"
          value="${author?.books[2]?.id}" />

Would allow individual entries in the books List to be selected separately.

Entries at particular indexes can be removed in the same way too. For example:

<g:select name="books[0].id"
          from="${Book.list()}"
          value="${author?.books[0]?.id}"
          noSelection="['null': '']"/>

Will render a select box that will remove the association at books[0] if the empty option is chosen.

Binding to a Map property works the same way except that the list index in the parameter name is replaced by the map key:

<g:select name="images[cover].id"
          from="${Image.list()}"
          value="${book?.images[cover]?.id}"
          noSelection="['null': '']"/>

This would bind the selected image into the Map property images under a key of "cover".

When binding to Maps, Arrays and Collections the data binder will automatically grow the size of the collections as necessary.

The default limit to how large the binder will grow a collection is 256. If the data binder encounters an entry that requires the collection be grown beyond that limit, the entry is ignored. The limit may be configured by assigning a value to the grails.databinding.autoGrowCollectionLimit property in application.groovy.
grails-app/conf/application.groovy
// the default value is 256
grails.databinding.autoGrowCollectionLimit = 128

// ...

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 it 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 Action Arguments

Controller action arguments are subject to request parameter data binding. There are 2 categories of controller action arguments. The first category is command objects. Complex types are treated as command objects. See the Command Objects section of the user guide for details. The other category is basic object types. Supported types are the 8 primitives, their corresponding type wrappers and java.lang.String. The default behavior is to map request parameters to action arguments by name:

class AccountingController {

   // accountNumber will be initialized with the value of params.accountNumber
   // accountType will be initialized with params.accountType
   def displayInvoice(String accountNumber, int accountType) {
       // ...
   }
}

For primitive arguments and arguments which are instances of any of the primitive type wrapper classes a type conversion has to be carried out before the request parameter value can be bound to the action argument. The type conversion happens automatically. In a case like the example shown above, the params.accountType request parameter has to be converted to an int. If type conversion fails for any reason, the argument will have its default value per normal Java behavior (null for type wrapper references, false for booleans and zero for numbers) and a corresponding error will be added to the errors property of the defining controller.

/accounting/displayInvoice?accountNumber=B59786&accountType=bogusValue

Since "bogusValue" cannot be converted to type int, the value of accountType will be zero, the controller’s errors.hasErrors() will be true, the controller’s errors.errorCount will be equal to 1 and the controller’s errors.getFieldError('accountType') will contain the corresponding error.

If the argument name does not match the name of the request parameter then the @grails.web.RequestParameter annotation may be applied to an argument to express the name of the request parameter which should be bound to that argument:

import grails.web.RequestParameter

class AccountingController {

   // mainAccountNumber will be initialized with the value of params.accountNumber
   // accountType will be initialized with params.accountType
   def displayInvoice(@RequestParameter('accountNumber') String mainAccountNumber, int accountType) {
       // ...
   }
}

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. This results in a type conversion error. Grails will retain type conversion errors inside the errors property of a Grails domain class. For example:

class Book {
    ...
    URL publisherURL
}

Here we have a domain class Book that uses the java.net.URL class to represent URLs. Given an incoming request such as:

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

it is not possible to bind the string a-bad-url to the publisherURL property as 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 from the grails-app/i18n/messages.properties file to use for the error. 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

The BindUsing Annotation

The BindUsing annotation may be used to define a custom binding mechanism for a particular field in a class. Any time data binding is being applied to the field the closure value of the annotation will be invoked with 2 arguments. The first argument is the object that data binding is being applied to and the second argument is DataBindingSource which is the data source for the data binding. The value returned from the closure will be bound to the property. The following example would result in the upper case version of the name value in the source being applied to the name field during data binding.

import grails.databinding.BindUsing

class SomeClass {
    @BindUsing({obj, source ->

        //source is DataSourceBinding which is similar to a Map
        //and defines getAt operation but source.name cannot be used here.
        //In order to get name from source use getAt instead as shown below.

        source['name']?.toUpperCase()
    })
    String name
}
Note that data binding is only possible when the name of the request parameter matches with the field name in the class. Here, name from request parameters matches with name from SomeClass.

The BindUsing annotation may be used to define a custom binding mechanism for all of the fields on a particular class. When the annotation is applied to a class, the value assigned to the annotation should be a class which implements the BindingHelper interface. An instance of that class will be used any time a value is bound to a property in the class that this annotation has been applied to.

@BindUsing(SomeClassWhichImplementsBindingHelper)
class SomeClass {
    String someProperty
    Integer someOtherProperty
}

The BindInitializer Annotation

The BindInitializer annotation may be used to initialize an associated field in a class if it is undefined. Unlike the BindUsing annotation, databinding will continue binding all nested properties on this association.

import grails.databinding.BindInitializer

class Account{}

class User {
  Account account

  // BindInitializer expects you to return a instance of the type
  // where it's declared on. You can use source as a parameter, in this case user.
  @BindInitializer({user-> new Contact(account:user.account) })
  Contact contact
}
class Contact{
  Account account
  String firstName
}
@BindInitializer only makes sense for associated entities, as per this use case.

Custom Data Converters

The binder will do a lot of type conversion automatically. Some applications may want to define their own mechanism for converting values and a simple way to do this is to write a class which implements ValueConverter and register an instance of that class as a bean in the Spring application context.

package com.myapp.converters

import grails.databinding.converters.ValueConverter

/**
 * A custom converter which will convert String of the
 * form 'city:state' into an Address object.
 */
class AddressValueConverter implements ValueConverter {

    boolean canConvert(value) {
        value instanceof String
    }

    def convert(value) {
        def pieces = value.split(':')
        new com.myapp.Address(city: pieces[0], state: pieces[1])
    }

    Class<?> getTargetType() {
        com.myapp.Address
    }
}

An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented ValueConverter will be automatically plugged in to the data binding process.

grails-app/conf/spring/resources.groovy
beans = {
    addressConverter com.myapp.converters.AddressValueConverter
    // ...
}
class Person {
    String firstName
    Address homeAddress
}

class Address {
    String city
    String state
}

def person = new Person()
person.properties = [firstName: 'Jeff', homeAddress: "O'Fallon:Missouri"]
assert person.firstName == 'Jeff'
assert person.homeAddress.city = "O'Fallon"
assert person.homeAddress.state = 'Missouri'

Date Formats For Data Binding

A custom date format may be specified to be used when binding a String to a Date value by applying the BindingFormat annotation to a Date field.

import grails.databinding.BindingFormat

class Person {
    @BindingFormat('MMddyyyy')
    Date birthDate
}

A global setting may be configured in application.groovy to define date formats which will be used application wide when binding to Date.

grails-app/conf/application.groovy
grails.databinding.dateFormats = ['MMddyyyy', 'yyyy-MM-dd HH:mm:ss.S', "yyyy-MM-dd'T'hh:mm:ss'Z'"]

The formats specified in grails.databinding.dateFormats will be attempted in the order in which they are included in the List. If a property is marked with @BindingFormat, the @BindingFormat will take precedence over the values specified in grails.databinding.dateFormats.

The formats configured by default are:

  • yyyy-MM-dd HH:mm:ss.S

  • yyyy-MM-dd’T’hh:mm:ss’Z'

  • yyyy-MM-dd HH:mm:ss.S z

  • yyyy-MM-dd’T’HH:mm:ss.SSSX

Custom Formatted Converters

You may supply your own handler for the BindingFormat annotation by writing a class which implements the FormattedValueConverter interface and registering an instance of that class as a bean in the Spring application context. Below is an example of a trivial custom String formatter that might convert the case of a String based on the value assigned to the BindingFormat annotation.

package com.myapp.converters

import grails.databinding.converters.FormattedValueConverter

class FormattedStringValueConverter implements FormattedValueConverter {
    def convert(value, String format) {
        if('UPPERCASE' == format) {
            value = value.toUpperCase()
        } else if('LOWERCASE' == format) {
            value = value.toLowerCase()
        }
        value
    }

    Class getTargetType() {
        // specifies the type to which this converter may be applied
        String
    }
}

An instance of that class needs to be registered as a bean in the Spring application context. The bean name is not important. All beans that implemented FormattedValueConverter will be automatically plugged in to the data binding process.

grails-app/conf/spring/resources.groovy
beans = {
    formattedStringConverter com.myapp.converters.FormattedStringValueConverter
    // ...
}

With that in place the BindingFormat annotation may be applied to String fields to inform the data binder to take advantage of the custom converter.

import grails.databinding.BindingFormat

class Person {
    @BindingFormat('UPPERCASE')
    String someUpperCaseString

    @BindingFormat('LOWERCASE')
    String someLowerCaseString

    String someOtherString
}

Localized Binding Formats

The BindingFormat annotation supports localized format strings by using the optional code attribute. If a value is assigned to the code attribute that value will be used as the message code to retrieve the binding format string from the messageSource bean in the Spring application context and that lookup will be localized.

import grails.databinding.BindingFormat

class Person {
    @BindingFormat(code='date.formats.birthdays')
    Date birthDate
}
# grails-app/conf/i18n/messages.properties
date.formats.birthdays=MMddyyyy
# grails-app/conf/i18n/messages_es.properties
date.formats.birthdays=ddMMyyyy

Structured Data Binding Editors

A structured data binding editor is a helper class which can bind structured request parameters to a property. The common use case for structured binding is binding to a Date object which might be constructed from several smaller pieces of information contained in several request parameters with names like birthday_month, birthday_date and birthday_year. The structured editor would retrieve all of those individual pieces of information and use them to construct a Date.

The framework provides a structured editor for binding to Date objects. An application may register its own structured editors for whatever types are appropriate. Consider the following classes:

src/main/groovy/databinding/Gadget.groovy
package databinding

class Gadget {
    Shape expandedShape
    Shape compressedShape
}
src/main/groovy/databinding/Shape.groovy
package databinding

class Shape {
    int area
}

A Gadget has 2 Shape fields. A Shape has an area property. It may be that the application wants to accept request parameters like width and height and use those to calculate the area of a Shape at binding time. A structured binding editor is well suited for that.

The way to register a structured editor with the data binding process is to add an instance of the grails.databinding.TypedStructuredBindingEditor interface to the Spring application context. The easiest way to implement the TypedStructuredBindingEditor interface is to extend the org.grails.databinding.converters.AbstractStructuredBindingEditor abstract class and override the getPropertyValue method as shown below:

src/main/groovy/databinding/converters/StructuredShapeEditor.groovy
package databinding.converters

import databinding.Shape

import org.grails.databinding.converters.AbstractStructuredBindingEditor

class StructuredShapeEditor extends AbstractStructuredBindingEditor<Shape> {

    public Shape getPropertyValue(Map values) {
        // retrieve the individual values from the Map
        def width = values.width as int
        def height = values.height as int

        // use the values to calculate the area of the Shape
        def area = width * height

        // create and return a Shape with the appropriate area
        new Shape(area: area)
    }
}

An instance of that class needs to be registered with the Spring application context:

grails-app/conf/spring/resources.groovy
beans = {
    shapeEditor databinding.converters.StructuredShapeEditor
    // ...
}

When the data binder binds to an instance of the Gadget class it will check to see if there are request parameters with names compressedShape and expandedShape which have a value of "struct" and if they do exist, that will trigger the use of the StructuredShapeEditor. The individual components of the structure need to have parameter names of the form propertyName_structuredElementName. In the case of the Gadget class above that would mean that the compressedShape request parameter should have a value of "struct" and the compressedShape_width and compressedShape_height parameters should have values which represent the width and the height of the compressed Shape. Similarly, the expandedShape request parameter should have a value of "struct" and the expandedShape_width and expandedShape_height parameters should have values which represent the width and the height of the expanded Shape.

grails-app/controllers/demo/DemoController.groovy
class DemoController {

    def createGadget(Gadget gadget) {
        /*
        /demo/createGadget?expandedShape=struct&expandedShape_width=80&expandedShape_height=30
                          &compressedShape=struct&compressedShape_width=10&compressedShape_height=3

        */

        // with the request parameters shown above gadget.expandedShape.area would be 2400
        // and gadget.compressedShape.area would be 30
        // ...
    }
}

Typically the request parameters with "struct" as their value would be represented by hidden form fields.

Data Binding Event Listeners

The DataBindingListener interface provides a mechanism for listeners to be notified of data binding events. The interface looks like this:

package grails.databinding.events;

import grails.databinding.errors.BindingError;

/**
 * A listener which will be notified of events generated during data binding.
 *
 * @author Jeff Brown
 * @since 3.0
 * @see DataBindingListenerAdapter
 */
public interface DataBindingListener {

    /**
     * @return true if the listener is interested in events for the specified type.
     */
    boolean supports(Class<?> clazz);

    /**
     * Called when data binding is about to start.
     *
     * @param target The object data binding is being imposed upon
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     * @return true if data binding should continue
     */
    Boolean beforeBinding(Object target, Object errors);

    /**
     * Called when data binding is about to imposed on a property
     *
     * @param target The object data binding is being imposed upon
     * @param propertyName The name of the property being bound to
     * @param value The value of the property being bound
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     * @return true if data binding should continue, otherwise return false
     */
    Boolean beforeBinding(Object target, String propertyName, Object value, Object errors);

    /**
     * Called after data binding has been imposed on a property
     *
     * @param target The object data binding is being imposed upon
     * @param propertyName The name of the property that was bound to
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     */
    void afterBinding(Object target, String propertyName, Object errors);

    /**
     * Called after data binding has finished.
     *
     * @param target The object data binding is being imposed upon
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     */
    void afterBinding(Object target, Object errors);

    /**
     * Called when an error occurs binding to a property
     * @param error encapsulates information about the binding error
     * @param errors the Spring Errors instance (a org.springframework.validation.BindingResult)
     * @see BindingError
     */
    void bindingError(BindingError error, Object errors);
}

Any bean in the Spring application context which implements that interface will automatically be registered with the data binder. The DataBindingListenerAdapter class implements the DataBindingListener interface and provides default implementations for all of the methods in the interface so this class is well suited for subclassing so your listener class only needs to provide implementations for the methods your listener is interested in.

Using The Data Binder Directly

There are situations where an application may want to use the data binder directly. For example, to do binding in a Service on some arbitrary object which is not a domain class. The following will not work because the properties property is read only.

src/main/groovy/bindingdemo/Widget.groovy
package bindingdemo

class Widget {
    String name
    Integer size
}
grails-app/services/bindingdemo/WidgetService.groovy
package bindingdemo

class WidgetService {

    def updateWidget(Widget widget, Map data) {
        // this will throw an exception because
        // properties is read-only
        widget.properties = data
    }
}

An instance of the data binder is in the Spring application context with a bean name of grailsWebDataBinder. That bean implements the DataBinder interface. The following code demonstrates using the data binder directly.

grails-app/services/bindingdmeo/WidgetService
package bindingdemo

import grails.databinding.SimpleMapDataBindingSource

class WidgetService {

    // this bean will be autowired into the service
    def grailsWebDataBinder

    def updateWidget(Widget widget, Map data) {
        grailsWebDataBinder.bind widget, data as SimpleMapDataBindingSource
    }

}

See the DataBinder documentation for more information about overloaded versions of the bind method.

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 and be persisted in 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 is to use Command Objects as the target of data binding instead of domain classes. 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)

The bindData method also lets you exclude certain parameters that you don’t want updated:

def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])

Or include only certain properties:

def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName']])
If an empty List is provided as a value for the include parameter then all fields will be subject to binding if they are not explicitly excluded.

The bindable constraint can be used to globally prevent data binding for certain properties.

8.1.6 Responding with JSON

Using the respond method to output JSON

The respond method is the preferred way to return JSON and integrates with Content Negotiation and JSON Views.

The respond method provides content negotiation strategies to intelligently produce an appropriate response for the given client.

For example given the following controller and action:

grails-app/controllers/example/BookController.groovy
package example

class BookController {
    def index() {
        respond Book.list()
    }
}

The respond method will take the followings steps:

  1. If the client Accept header specifies a media type (for example application/json) use that

  2. If the file extension of the URI (for example /books.json) includes a format defined in the grails.mime.types property of grails-app/conf/application.yml use the media type defined in the configuration

The respond method will then look for an appriopriate Renderer for the object and the calculated media type from the RendererRegistry.

Grails includes a number of pre-configured Renderer implementations that will produce default representations of JSON responses for the argument passed to respond. For example going to the /book.json URI will produce JSON such as:

[
    {id:1,"title":"The Stand"},
    {id:2,"title":"Shining"}
]

Controlling the Priority of Media Types

By default if you define a controller there is no priority in terms of which format is sent back to the client and Grails assumes you wish to serve HTML as a response type.

However if your application is primarily an API, then you can specify the priorty using the responseFormats property:

grails-app/controllers/example/BookController.groovy
package example

class BookController {
    static responseFormats = ['json', 'html']
    def index() {
        respond Book.list()
    }
}

In the above example Grails will respond by default with json if the media type to respond with cannot be calculated from the Accept header or file extension.

Using Views to Output JSON Responses

If you define a view (either a GSP or a JSON View) then Grails will render the view when using the respond method by calculating a model from the argument passed to respond.

For example, in the previous listing, if you were to define grails-app/views/index.gson and grails-app/views/index.gsp views, these would be used if the client requested application/json or text/html media types respectively. Thus allowing you to define a single backend capable of serving responses to a web browser or representing your application’s API.

When rendering the view, Grails will calculate a model to pass to the view based on the type of the value passed to the respond method.

The following table summarizes this convention:

Example Argument Type Calculated Model Variable

respond Book.list()

java.util.List

bookList

respond( [] )

java.util.List

emptyList

respond Book.get(1)

example.Book

book

respond( [1,2] )

java.util.List

integerList

respond( [1,2] as Set )

java.util.Set

integerSet

respond( [1,2] as Integer[] )

Integer[]

integerArray

Using this convention you can reference the argument passed to respond from within your view:

grails-app/views/book/index.gson
@Field List<Book> bookList = []

json bookList, { Book book ->
    title book.title
}

You will notice that if Book.list() returns an empty list then the model variable name is translated to emptyList. This is by design and you should provide a default value in the view if no model variable is specified, such as the List in the example above:

grails-app/views/book/index.gson
// defaults to an empty list
@Field List<Book> bookList = []
...

There are cases where you may wish to be more explicit and control the name of the model variable. For example if you have a domain inheritance hierarchy where a call to list() my return different child classes relying on automatic calculation may not be reliable.

In this case you should pass the model directly using respond and a map argument:

respond bookList: Book.list()
When responding with any kind of mixed argument types in a collection, always use an explicit model name.

If you simply wish to augment the calculated model then you can do so by passing a model argument:

respond Book.list(), [model: [bookCount: Book.count()]]

The above example will produce a model like [bookList:books, bookCount:totalBooks], where the calculated model is combined with the model passed in the model argument.

Using the render method to output JSON

The render method can also be used to output JSON, but should only be used for simple cases that don’t warrant the creation of a JSON view:

def list() {

    def results = Book.list()

    render(contentType: "application/json") {
        books(results) { Book b ->
            title b.title
        }
    }
}

In this case the result would be something along the lines of:

[
    {"title":"The Stand"},
    {"title":"Shining"}
]
This technique for rendering JSON may be ok for very simple responses, but in general you should favour the use of JSON Views and use the view layer rather than embedding logic in your application.

The same dangers with naming conflicts described above for XML also apply to JSON building.

8.1.7 More on JSONBuilder

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

For JSON, since Grails 3.1, Grails uses Groovy’s StreamingJsonBuilder by default and you can refer to the Groovy documentation and StreamingJsonBuilder API documentation on how to use it.

8.1.8 Responding with XML

8.1.9 Uploading Files

Programmatic File Uploads

Grails supports file uploads using Spring’s MultipartHttpServletRequest interface. The first step for file uploading is to create a multipart form like this:

Upload Form: <br />
    <g:uploadForm action="upload">
        <input type="file" name="myFile" />
        <input type="submit" />
    </g:uploadForm>

The uploadForm tag conveniently adds the enctype="multipart/form-data" attribute to the standard <g:form> tag.

There are then a number of ways to handle the file upload. One is to work with the Spring MultipartFile instance directly:

def upload() {
    def f = request.getFile('myFile')
    if (f.empty) {
        flash.message = 'file cannot be empty'
        render(view: 'uploadForm')
        return
    }

    f.transferTo(new File('/some/local/dir/myfile.txt'))
    response.sendError(200, 'Done')
}

This is convenient for doing transfers to other destinations and manipulating the file directly as you can obtain an InputStream and so on with the MultipartFile interface.

File Uploads through Data Binding

File uploads can also be performed using data binding. Consider this Image domain class:

class Image {
    byte[] myFile

    static constraints = {
        // Limit upload file size to 2MB
        myFile maxSize: 1024 * 1024 * 2
    }
}

If you create an image using the params object in the constructor as in the example below, Grails will automatically bind the file’s contents as a byte[] to the myFile property:

def img = new Image(params)

It’s important that you set the size or maxSize constraints, otherwise your database may be created with a small column size that can’t handle reasonably sized files. For example, both H2 and MySQL default to a blob size of 255 bytes for byte[] properties.

It is also possible to set the contents of the file as a string by changing the type of the myFile property on the image to a String type:

class Image {
   String myFile
}

Increase Upload Max File Size

Grails default size for file uploads is 128000 (~128KB). When this limit is exceeded you’ll see the following exception:

org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException

You can configure the limit in your application.yml as follows:

grails-app/conf/application.yml
grails:
    controllers:
        upload:
            maxFileSize: 2000000
            maxRequestSize: 2000000

maxFileSize = The maximum size allowed for uploaded files.

maxRequestSize = The maximum size allowed for multipart/form-data requests.

Limit the file size to a maximum value in order to prevent denial of service attacks.

These limits exist to prevent DoS attacks and to enforce overall application performance

8.1.10 Command Objects

Grails controllers support the concept of command objects. A command object is a class that is used in conjunction with data binding, usually to allow validation of data that may not fit into an existing domain class.

A class is only considered to be a command object when it is used as a parameter of an action.

Declaring Command Objects

Command object classes are defined just like any other class.

class LoginCommand implements grails.validation.Validateable {
    String username
    String password

    static constraints = {
        username(blank: false, minSize: 6)
        password(blank: false, minSize: 6)
    }
}

In this example, the command object class implements the Validateable trait. The Validateable trait allows the definition of Constraints just like in domain classes. If the command object is defined in the same source file as the controller that is using it, Grails will automatically make it Validateable. It is not required that command object classes be validateable.

By default, all Validateable object properties which are not instances of java.util.Collection or java.util.Map are nullable: false. Instances of java.util.Collection and java.util.Map default to nullable: true. If you want a Validateable that has nullable: true properties by default, you can specify this by defining a defaultNullable method in the class:

class AuthorSearchCommand implements grails.validation.Validateable {
    String  name
    Integer age

    static boolean defaultNullable() {
        true
    }
}

In this example, both name and age will allow null values during validation.

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 and initialize.

Before the controller action is executed Grails will automatically create an instance of the command object class and populate its properties by binding the request parameters. If the command object class is marked with Validateable then the command object will be validated. For example:

class LoginController {

    def login(LoginCommand cmd) {
        if (cmd.hasErrors()) {
            redirect(action: 'loginForm')
            return
        }

        // work with the command object data
    }
}

If the command object’s type is that of a domain class and there is an id request parameter then instead of invoking the domain class constructor to create a new instance a call will be made to the static get method on the domain class and the value of the id parameter will be passed as an argument.

Whatever is returned from that call to get is what will be passed into the controller action. This means that if there is an id request parameter and no corresponding record is found in the database then the value of the command object will be null. If an error occurs retrieving the instance from the database then null will be passed as an argument to the controller action and an error will be added the controller’s errors property.

If the command object’s type is a domain class and there is no id request parameter or there is an id request parameter and its value is empty then null will be passed into the controller action unless the HTTP request method is "POST", in which case a new instance of the domain class will be created by invoking the domain class constructor. For all of the cases where the domain class instance is non-null, data binding is only performed if the HTTP request method is "POST", "PUT" or "PATCH".

Command Objects And Request Parameter Names

Normally request parameter names will be mapped directly to property names in the command object. Nested parameter names may be used to bind down the object graph in an intuitive way.

In the example below a request parameter named name will be bound to the name property of the Person instance and a request parameter named address.city will be bound to the city property of the address property in the Person.

class StoreController {
    def buy(Person buyer) {
        // ...
    }
}

class Person {
    String name
    Address address
}

class Address {
    String city
}

A problem may arise if a controller action accepts multiple command objects which happen to contain the same property name. Consider the following example.

class StoreController {
    def buy(Person buyer, Product product) {
        // ...
    }
}

class Person {
    String name
    Address address
}

class Address {
    String city
}

class Product {
    String name
}

If there is a request parameter named name it isn’t clear if that should represent the name of the Product or the name of the Person. Another version of the problem can come up if a controller action accepts 2 command objects of the same type as shown below.

class StoreController {
    def buy(Person buyer, Person seller, Product product) {
        // ...
    }
}

class Person {
    String name
    Address address
}

class Address {
    String city
}

class Product {
    String name
}

To help deal with this the framework imposes special rules for mapping parameter names to command object types. The command object data binding will treat all parameters that begin with the controller action parameter name as belonging to the corresponding command object.

For example, the product.name request parameter will be bound to the name property in the product argument, the buyer.name request parameter will be bound to the name property in the buyer argument the seller.address.city request parameter will be bound to the city property of the address property of the seller argument, etc…​

Command Objects and Dependency Injection

Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic which uses a Grails service:

class LoginCommand implements grails.validation.Validateable {

    def loginService

    String username
    String password

    static constraints = {
        username validator: { val, obj ->
            obj.loginService.canLogin(obj.username, obj.password)
        }
    }
}

In this example the command object interacts with the loginService bean which is injected by name from the Spring ApplicationContext.

Binding The Request Body To Command Objects

When a request is made to a controller action which accepts a command object and the request contains a body, Grails will attempt to parse the body of the request based on the request content type and use the body to do data binding on the command object. See the following example.

grails-app/controllers/bindingdemo/DemoController.groovy
package bindingdemo

class DemoController {

    def createWidget(Widget w) {
        render "Name: ${w?.name}, Size: ${w?.size}"
    }
}

class Widget {
    String name
    Integer size
}
$ curl -H "Content-Type: application/json" -d '{"name":"Some Widget","42"}'[size] localhost:8080/demo/createWidget
 Name: Some Widget, Size: 42

$ curl -H "Content-Type: application/xml" -d '<widget><name>Some Other Widget</name><size>2112</size></widget>' localhost:8080/bodybind/demo/createWidget
 Name: Some Other Widget, Size: 2112

The request body will not be parsed under the following conditions:

  • The request method is GET

  • The request method is DELETE

  • The content length is 0

Note that the body of the request is being parsed to make that work. Any attempt to read the body of the request after that will fail since the corresponding input stream will be empty. The controller action can either use a command object or it can parse the body of the request on its own (either directly, or by referring to something like request.JSON), but cannot do both.

grails-app/controllers/bindingdemo/DemoController.groovy
package bindingdemo

class DemoController {

    def createWidget(Widget w) {
        // this will fail because it requires reading the body,
        // which has already been read.
        def json = request.JSON

        // ...

    }
}

Working with Lists of Command Objects

A common use case for command objects is a Command Object that contains a collection of another:

class DemoController {

    def createAuthor(AuthorCommand command) {
        // ...

    }

    class AuthorCommand {
        String fullName
        List<BookCommand> books
    }

    class BookCommand {
        String title
        String isbn
    }
}

On this example, we want to create an Author with multiple Books.

In order to make this work from the UI layer, you can do the following in your GSP:

<g:form name="submit-author-books" controller="demo" action="createAuthor">
    <g:fieldValue name="fullName" value=""/>
    <ul>
        <li>
            <g:fieldValue name="books[0].title" value=""/>
            <g:fieldValue name="books[0].isbn" value=""/>
        </li>

        <li>
            <g:fieldValue name="books[1].title" value=""/>
            <g:fieldValue name="books[1].isbn" value=""/>
        </li>
    </ul>
</g:form>

There is also support for JSON, so you can submit the following with correct databinding

{
    "fullName": "Graeme Rocher",
    "books": [{
        "title": "The Definitive Guide to Grails",
        "isbn": "1111-343455-1111"
    }, {
        "title": "The Definitive Guide to Grails 2",
        "isbn": "1111-343455-1112"
    }],
}

8.1.11 Handling Duplicate Form Submissions

Grails has built-in support for handling duplicate form submissions using the "Synchronizer Token Pattern". To get started you 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:

<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 or clustered sessions if used in a cluster.

8.1.12 Simple Type Converters

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, and there are also methods for boolean, long, char, short and so on. Each of these methods is null-safe and safe from any parsing errors, so you don’t have to perform any additional checks on the parameters.

Each of the conversion methods allows a default value to be passed as an optional second argument. The default value will be returned if a corresponding entry cannot be found in the map or if an error occurs during the conversion. Example:

def total = params.int('total', 42)

These same type conversion methods are also available on the attrs 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 one 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
}

8.1.13 Declarative Controller Exception Handling

Grails controllers support a simple mechanism for declarative exception handling. If a controller declares a method that accepts a single argument and the argument type is java.lang.Exception or some subclass of java.lang.Exception, that method will be invoked any time an action in that controller throws an exception of that type. See the following example.

grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

    def someAction() {
        // do some work
    }

    def handleSQLException(SQLException e) {
        render 'A SQLException Was Handled'
    }

    def handleBatchUpdateException(BatchUpdateException e) {
        redirect controller: 'logging', action: 'batchProblem'
    }

    def handleNumberFormatException(NumberFormatException nfe) {
        [problemDescription: 'A Number Was Invalid']
    }
}

That controller will behave as if it were written something like this…​

grails-app/controllers/demo/DemoController.groovy
package demo

class DemoController {

    def someAction() {
        try {
            // do some work
        } catch (BatchUpdateException e) {
            return handleBatchUpdateException(e)
        } catch (SQLException e) {
            return handleSQLException(e)
        } catch (NumberFormatException e) {
            return handleNumberFormatException(e)
        }
    }

    def handleSQLException(SQLException e) {
        render 'A SQLException Was Handled'
    }

    def handleBatchUpdateException(BatchUpdateException e) {
        redirect controller: 'logging', action: 'batchProblem'
    }

    def handleNumberFormatException(NumberFormatException nfe) {
        [problemDescription: 'A Number Was Invalid']
    }
}

The exception handler method names can be any valid method name. The name is not what makes the method an exception handler, the Exception argument type is the important part.

The exception handler methods can do anything that a controller action can do including invoking render, redirect, returning a model, etc.

One way to share exception handler methods across multiple controllers is to use inheritance. Exception handler methods are inherited into subclasses so an application could define the exception handlers in an abstract class that multiple controllers extend from. Another way to share exception handler methods across multiple controllers is to use a trait, as shown below…​

src/main/groovy/com/demo/DatabaseExceptionHandler.groovy
package com.demo

trait DatabaseExceptionHandler {
    def handleSQLException(SQLException e) {
        // handle SQLException
    }

    def handleBatchUpdateException(BatchUpdateException e) {
        // handle BatchUpdateException
    }
}
grails-app/controllers/com/demo/DemoController.groovy
package com.demo

class DemoController implements DatabaseExceptionHandler {

    // all of the exception handler methods defined
    // in DatabaseExceptionHandler will be added to
    // this class at compile time
}

Exception handler methods must be present at compile time. Specifically, exception handler methods which are runtime metaprogrammed onto a controller class are not supported.

8.2 Groovy Server Pages

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.

Although GSP can render any format, not just HTML, it is more designed around rendering markup. If you are looking for a way to simplify JSON responses take a look at JSON Views.

GSP was previously part of Grails core, but since version 3.3 it is an independent Grails plugin that can be used by defining the following dependency in your build.gradle:

build.gradle
dependencies {
    //...
    implementation "org.apache.grails:grails-gsp:7.0.0-SNAPSHOT"
}

In addition, for production compilation you should apply the grails-gsp Gradle plugin:

build.gradle
apply plugin: "org.apache.grails:grails-gsp"

GSPs live in the grails-app/views directory and are typically rendered automatically (by convention) or with 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 referenced within the GSP view using the name book:

${book.title}
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation on XSS prevention for information on how to prevent XSS attacks.

8.2.1 GSP Basics

In 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 <% %> scriptlet blocks to embed Groovy code (again this is discouraged):

<html>
   <body>
     <% out << "Hello GSP!" %>
   </body>
</html>

You can also use the <%= %> syntax to output values:

<html>
   <body>
     <%="Hello GSP!" %>
   </body>
</html>

GSP also supports JSP-style server-side comments (which are not rendered in the HTML response) as the following example demonstrates:

<html>
   <body>
     <%-- This is my comment --%>
     <%="Hello GSP!" %>
   </body>
</html>
Embedding data received from user input has the risk of making your application vulnerable to an Cross Site Scripting (XSS) attack. Please read the documentation under XSS prevention for information on how to prevent XSS attacks.

8.2.1.1 Variables and Scopes

Within the <% %> brackets you can declare variables:

<% now = new Date() %>

and then access those variables later in the page:

<%=now%>

Within the scope of a GSP there are a number of pre-defined variables, including:

  • application - The {javaee}javax/servlet/ServletContext.html[javax.servlet.ServletContext] instance

  • applicationContext The Spring ApplicationContext instance

  • flash - The flash object

  • grailsApplication - The ../apigrails/core/GrailsApplication.html[GrailsApplication] instance

  • out - The response writer for writing to the output stream

  • params - The params object for retrieving request parameters

  • request - The {javaee}javax/servlet/http/HttpServletRequest.html[HttpServletRequest] instance

  • response - The {javaee}javax/servlet/http/HttpServletResponse.html[HttpServletResponse] instance

  • session - The {javaee}javax/servlet/http/HttpSession.html[HttpSession] instance

  • webRequest - The ../apiorg/grails/web/servlet/mvc/GrailsWebRequest.html[GrailsWebRequest] instance

8.2.1.2 Logic and Iteration

Using the <% %> syntax you can embed loops and so on using this syntax:

<html>
   <body>
      <% [1,2,3,4].each { num -> %>
         <p><%="Hello ${num}!" %></p>
      <%}%>
   </body>
</html>

As well as logical branching:

<html>
   <body>
      <% if (params.hello == 'true')%>
      <%="Hello!"%>
      <% else %>
      <%="Goodbye!"%>
   </body>
</html>

8.2.1.3 Page Directives

GSP also supports a few JSP-style page directives.

The import directive lets you import classes into the page. However, it is rarely needed due to Groovy’s default imports and GSP Tags:

<%@ page import="java.awt.*" %>

Separate imports with semicolons ;. As a convention, you should split larger number of imports into separate lines to improve readability, which requires adding backslash \ at the end of each line:

<%@ page import="java.awt.*; \
your.custom.ComponentA; \
your.custom.ComponentB;"
%>

GSP also supports the contentType directive:

<%@ page contentType="application/json" %>

The contentType directive allows using GSP to render other formats.

8.2.1.4 Expressions

In GSP the <%= %> syntax introduced earlier is rarely used due to the support for GSP expressions. 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 ${..} block.

Embedding data received from user input has the risk of making your application vulnerable to a Cross Site Scripting (XSS) attack. Please read the documentation under XSS prevention for information on how to prevent XSS attacks.

8.2.2 GSP Tags

Now that the less attractive JSP heritage has been set aside, the following sections cover GSP’s built-in tags, which are the preferred 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 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:

<g:example attr="${new Date()}" attr2="[one:1, two:2, three:3]">
   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:'one', two:'two']">
   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.

8.2.2.1 Variables and Scopes

Variables can be defined within a GSP using the set tag:

<g:set var="now" value="${new Date()}" />

Here we assign a variable called 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:

<g:set var="myHTML">
   Some re-usable code on: ${new Date()}
</g:set>

The assigned value can also be a bean from the applicationContext:

<g:set var="bookService" bean="bookService" />

Variables can also be placed in one of the following scopes:

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

To specify the scope, use the scope attribute:

<g:set var="now" value="${new Date()}" scope="request" />

8.2.2.2 Logic and Iteration

GSP also supports logical and iterative tags out of the box. For logic there are if, else and elseif tags for use with branching:

<g:if test="${session.role == 'admin'}">
   <%-- show administrative functions --%>
</g:if>
<g:else>
   <%-- show basic functions --%>
</g:else>

Use each and while tags for iteration:

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

8.2.2.3 Search and Filtering

If you have collections of objects you often need to sort and filter them. Use the findAll and grep tags for these tasks:

Stephen King's Books:
<g:findAll in="${books}" expr="it.author == 'Stephen King'">
     <p>Title: ${it.title}</p>
</g:findAll>

The expr attribute contains a Groovy expression that can be used as a filter. The grep tag does a similar job, for example filtering by class:

<g:grep in="${books}" filter="NonFictionBooks.class">
     <p>Title: ${it.title}</p>
</g:grep>

Or using a regular expression:

<g:grep in="${books.title}" filter="~/.*?Groovy.*?/">
     <p>Title: ${it}</p>
</g:grep>

The above example is also interesting due to its usage of GPath. GPath is an XPath-like language in Groovy. The books variable is a collection of Book instances. Since each Book has a title, you can obtain a list of Book titles using the expression books.title. Groovy will auto-magically iterate the collection, obtain each title, and return a new list!

8.2.2.4 Links and Resources

GSP also features tags to help you manage linking to controllers and actions. The link tag lets you specify controller and action name pairing and it will automatically work out the link based on the URL Mappings, even if you change them! For example:

<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 params="[sort: 'title', order: 'asc', author: currentBook.author]"
        action="list">Book List</g:link>

8.2.2.5 Forms and Fields

Form Basics

GSP supports many different tags for working with HTML forms and fields, the most basic of which is the form tag. This is a controller/action aware version of the regular HTML form tag. The url attribute lets you specify which controller and action to map to:

<g:form name="myForm" url="[controller:'book',action:'list']">...</g:form>

In this case we create a form called myForm that submits to the BookController's list action. Beyond that, all the usual HTML attributes apply.

Form Fields

In addition to easy construction of forms, GSP supports custom tags for dealing with different types of fields, including:

  • textField - For input fields of type 'text'

  • passwordField - For input fields of type 'password'

  • 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

Each of these allows GSP expressions for the value:

<g:textField name="myField" value="${myValue}" />

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 locales, currencies and time zones respectively).

Multiple Submit Buttons

The age-old problem of dealing with multiple submit buttons is also handled elegantly with Grails using the formActionSubmit tag. It is just like a regular submit, but lets you specify an alternative controller & action to submit to:

<g:formActionSubmit value="Some update label" controller="mycontroller" action="update" />

8.2.2.6 Tags as Method Calls

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 controllers, tag libraries or GSP views.

Tags as method calls from GSPs

Tags return their results as a String-like object (a StreamCharBuffer which has all of the same methods as String) instead of writing directly to the response when called as methods. For example:

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

This is particularly useful for using 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 WYSIWYG tools 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 StreamCharBuffer result is returned:

def imageLocation = createLinkTo(dir:"images", file:"logo.jpg").toString()

Prefix the namespace to avoid naming conflicts:

def imageLocation = g.createLinkTo(dir:"images", file:"logo.jpg").toString()

For tags that use a custom namespace, use that prefix for the method call. For example (from the CK Editor plugin):

def editor = ckeditor.editor(name: "text", width: "100%", height: "400")

8.2.3 Views and Templates

Grails also has the concept of templates. These are useful for partitioning your views into maintainable chunks, and combined with Layouts provide a highly re-usable mechanism for structured 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, you might have a template that renders Books located at grails-app/views/book/_bookTemplate.gsp:

<div class="book" id="${book?.id}">
   <div>Title: ${book?.title}</div>
   <div>Author: ${book?.author?.name}</div>
</div>

Use the render tag to render this template from one of the views in grails-app/views/book:

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

Notice how we pass into a model to use using the 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 with a collection attribute:

<g:render template="bookTemplate" var="book" collection="${bookList}" />

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 an absolute location starting with / instead of a relative location. For example if you had a template called grails-app/views/shared/_mySharedTemplate.gsp, you would reference it as:

<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 controller method. This is useful for JavaScript heavy applications where you generate small HTML or data responses to partially update the current page instead of performing new request:

def bookData() {
    def b = Book.get(params.id)
    render(template:"bookTemplate", model:[book:b])
}

The render controller method writes directly to the response, which is the most common behaviour. To instead obtain the result of template as a String you can use the xref:../ref/Tags%20-%20GSP/render.html">render tag:

def bookData() {
    def b = Book.get(params.id)
    String content = g.render(template:"bookTemplate", model:[book:b])
    render content
}

Notice the usage of the g namespace which tells Grails we want to use the tag as method call instead of the render method.

8.2.4 Layouts with Sitemesh

Creating Layouts

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

<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--></div>
        <div class="body">
            <g:layoutBody />
        </div>
    </body>
</html>

The key elements are the layoutHead, layoutTitle and layoutBody tag invocations:

  • layoutTitle - outputs the target page’s title

  • layoutHead - outputs the target page’s head tag contents

  • layoutBody - outputs the target page’s body tag contents

The previous example also demonstrates the pageProperty tag which can be used to inspect and return aspects of the target page.

Triggering Layouts

There are a few ways to trigger a layout. The simplest is to add a meta tag to the view:

<html>
    <head>
        <title>An Example Page</title>
        <meta name="layout" content="main" />
    </head>
    <body>This is my content!</body>
</html>

In this case a layout called grails-app/views/layouts/main.gsp will be used to lay out the page. If we were to use the layout from the previous section the output would resemble this:

<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 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 this controller:

class BookController {
    def list() { /*...*/ }
}

You can create a layout called grails-app/views/layouts/book.gsp, 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 is not located using any of those conventions, the convention of last resort is to look for the application default layout which is grails-app/views/layouts/application.gsp. The name of the application default layout may be changed by defining the property grails.sitemesh.default.layout in the application configuration as follows:

grails-app/conf/application.yml
grails.sitemesh.default.layout: myLayoutName

With that property in place, the application default layout will be grails-app/views/layouts/myLayoutName.gsp.

Inline Layouts

Grails' also supports Sitemesh’s concept of inline layouts with the applyLayout tag. This can be used to apply a layout to a template, URL or arbitrary section of content. This lets you 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="https://www.google.com" />

<g:applyLayout name="myLayout">
The content to apply a layout to
</g:applyLayout>

Server-Side Includes

While the applyLayout tag is useful for applying layouts to external content, if you simply want to include external content in the current page you use the include tag:

<g:include controller="book" action="list" />

You can even combine the include tag and the applyLayout tag for added flexibility:

<g:applyLayout name="myLayout">
   <g:include controller="book" action="list" />
</g:applyLayout>

Finally, you can also call the include tag from a controller or tag library as a method:

def content = include(controller:"book", action:"list")

The resulting content will be provided via the return value of the include tag.

8.2.4.1 Sitemesh Content Blocks

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, partition the page to be decorated using the <content> tag:

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

Then within the layout you can reference these components and apply individual layouts to each:

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

8.2.5 Static Resources

Since version 3, Grails integrates with the Asset Pipeline plugin to provide sophisticated static asset management. This plugin is installed by default in new Grails applications.

The basic way to include a link to a static asset in your application is to use the resource tag. This simple approach creates a URI pointing to the file.

However, modern applications with dependencies on multiple JavaScript and CSS libraries and frameworks (as well as dependencies on multiple Grails plugins) require something more powerful.

The issues that the Asset-Pipeline plugin tackles are:

  • Reduced Dependence - The plugin has compression, minification, and cache-digests built in.

  • Easy Debugging - Makes for easy debugging by keeping files separate in development mode.

  • Asset Bundling using require directives.

  • Web application performance tuning is difficult.

  • The need for a standard way to expose static assets in plugins and applications.

  • The need for extensible processing to make languages like LESS or Coffee first class citizens.

The asset-pipeline allows you to define your javascript or css requirements right at the top of the file, and they get compiled on War creation.

Take a look at the documentation for the asset-pipeline to get started.

If you do not want to use the Asset-Pipeline plugin, you can serve the static assets from directories src/main/resources/public or src/main/webapp, but the latter one only gets included in WAR packaging but not in JAR packaging.

For example, if you had a file stored at /src/main/resources/public/images/example.jpg and your Grails application was running on port 8080, then you could access the file by navigating to http://localhost:8080/static/images/example.jpg.

Cache Configuration for Static Resources

By default, files under src/main/resources/public or src/main/webapp are served with an HTTP response header of Cache-Control: no-store. To have them be cached by the browser, you can set the configuration setting grails.resources.cachePeriod: number in application.yml so that they are served with a response header of Cache-Control: max-age=number indicating to the browser how many seconds the file should be considered fresh.

8.2.6 Making Changes to a Deployed Application

One of the main issues with deploying a Grails application (or typically any servlet-based application) is that any change to the views requires that you 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 properties to the application configuration:

grails-app/conf/application.yml
grails.gsp.enable.reload: true
grails.gsp.view.dir: /var/www/grails/my-app/

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 until you restart. 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.

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:

mkdir -p /var/www/grails/my-app/grails-app/views
cp -R grails-app/views/* /var/www/grails/my-app/grails-app/views

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.

There are also some system properties to control GSP reloading:

Name Description Default

grails.gsp.enable.reload

system property for enabling the GSP reload mode (alternative to adding it in the file-based application configuration

grails.gsp.reload.interval

interval between checking the lastmodified time of the gsp source file, unit is milliseconds

5000

grails.gsp.reload.granularity

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

1000

GSP reloading is supported for precompiled GSPs since Grails 1.3.5.

8.2.7 Tag Libraries

Like Java Server Pages (JSP), GSP supports the concept of custom tag libraries. Unlike JSP, Grails' tag library mechanism is simple, 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:

class SimpleTagLib {

}

Now to create a tag create a Closure property that takes two arguments: the tag attributes and the body content:

class SimpleTagLib {
    def simple = { attrs, body ->

    }
}

The attrs argument is a Map of the attributes of the tag, whilst the body argument is a Closure that returns the body content when invoked:

class SimpleTagLib {
    def emoticon = { attrs, body ->
       out << body() << (attrs.happy == 'true' ? " :-)" : " :-(")
    }
}

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 reference the tag inside your GSP; no imports are necessary:

<g:emoticon happy="true">Hi John</g:emoticon>
To help IDEs autocomplete tag attributes, you should add Javadoc comments to your tag closures with @attr descriptions. Since taglibs use Groovy code it can be difficult to reliably detect all usable attributes.

For example:

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' ? " :-)" : " :-(")
    }
}

and any mandatory attributes should include the REQUIRED keyword, e.g.

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)
    }
}

8.2.7.1 Variables and Scopes

Within 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 ../apigrails/core/GrailsApplication.html[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 {javaee}javax/servlet/http/HttpServletRequest.html[HttpServletRequest] instance

  • response - The {javaee}javax/servlet/http/HttpServletResponse.html[HttpServletResponse] instance

  • servletContext - The {javaee}javax/servlet/ServletContext.html[javax.servlet.ServletContext] instance

  • session - The {javaee}javax/servlet/http/HttpSession.html[HttpSession] instance

8.2.7.2 Simple Tags

As demonstrated in the previous example it is easy to write simple tags that have no body and just output content. Another example is a dateFormat style tag:

def dateFormat = { attrs, body ->
    out << new java.text.SimpleDateFormat(attrs.format).format(attrs.date)
}

The above uses Java’s SimpleDateFormat class to format a date and then write it to the response. The tag can then be used within a GSP as follows:

<g:dateFormat format="dd-MM-yyyy" date="${new Date()}" />

With simple tags sometimes you need to write HTML mark-up to the response. One approach would be to embed the content directly:

def formatBook = { attrs, body ->
    out << "<div id=\"${attrs.book.id}\">"
    out << "Title : ${attrs.book.title}"
    out << "</div>"
}

Although this approach may be tempting it is not very clean. A better approach would be to reuse the render tag:

def formatBook = { attrs, body ->
    out << render(template: "bookTemplate", model: [book: attrs.book])
}

And then have a separate GSP template that does the actual rendering.

8.2.7.3 Logical Tags

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

def isAdmin = { attrs, body ->
    def user = attrs.user
    if (user && checkUserPrivs(user)) {
        out << body()
    }
}

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:

<g:isAdmin user="${myUser}">
    // some restricted content
</g:isAdmin>

8.2.7.4 Iterative Tags

Iterative tags are easy too, since you can invoke the body multiple times:

def repeat = { attrs, body ->
    attrs.times?.toInteger()?.times { num ->
        out << body(num)
    }
}

In this example we check for a times attribute and if it exists convert it to a number, then use Groovy’s times method to iterate the specified number of times:

<g:repeat times="3">
<p>Repeat this 3 times! Current repeat = ${it}</p>
</g:repeat>

Notice how in this example we use the implicit 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:

out << body(num)

That value is then passed as the default variable it to the tag. However, if you have nested tags this can lead to conflicts, so you should instead name the variables that the body uses:

def repeat = { attrs, body ->
    def var = attrs.var ?: "num"
    attrs.times?.toInteger()?.times { num ->
        out << body((var):num)
    }
}

Here we check if there is a 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:

<g:repeat times="3" var="j">
<p>Repeat this 3 times! Current repeat = ${j}</p>
</g:repeat>

Notice how we use the 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.

8.2.7.5 Tag Namespaces

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:

out << my.example(name:"foo")

This works from GSP, controllers or tag libraries

8.2.7.6 Using JSP Tag Libraries

In addition to the simplified tag library mechanism provided by GSP, you can also use JSP tags from GSP.

In order to use JSP support you must ensure you have the grails-web-jsp dependency on your classpath by adding it to your build.gradle file:

build.gradle
dependencies {
    //...
    runtimeOnly "org.grails:grails-web-jsp:7.0.0-SNAPSHOT"
}

Then you will need to declare the JSP taglib to use with the taglib directive at the top of your GSP file:

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Besides this you have to configure Grails to scan for the JSP tld files. This is configured with the grails.gsp.tldScanPattern setting. It accepts a comma separated String value. Spring’s PathMatchingResourcePatternResolver is used to resolve the patterns.

For example, you could scan for all available tld files by adding this to application.yml:

grails-app/conf/application.yml
grails:
    gsp:
        tldScanPattern: 'classpath*:/META-INF/*.tld,/WEB-INF/tld/*.tld'

JSTL standard library is no longer added as a dependency by default. In case you are using JSTL, you should also add these dependencies to build.gradle:

build.gradle
dependencies {
    //...
    runtimeOnly 'javax.servlet:jstl:1.1.2'
    runtimeOnly 'taglibs:standard:1.1.2'
}

Then you can use JSP tags like any other tag:

<fmt:formatNumber value="${10}" pattern=".00"/>

With the added bonus that you can invoke JSP tags like methods:

${fmt.formatNumber(value:10, pattern:".00")}

8.2.7.7 Tag return value

A taglib can be used in a GSP as an ordinary tag, or it might be used as a function in other taglibs or GSP expressions.

Internally Grails intercepts calls to taglib closures. The "out" that is available in a taglib is mapped to a java.io.Writer implementation that writes to a buffer that "captures" the output of the taglib call. This buffer is the return value of a tag library call when it’s used as a function.

If the tag is listed in the library’s static returnObjectForTags array, then its return value will be written to the output when it’s used as a normal tag. The return value of the tag lib closure will be returned as-is if it’s used as a function in GSP expressions or other taglibs.

If the tag is not included in the returnObjectForTags array, then its return value will be discarded. Using "out" to write output in returnObjectForTags is not supported.

Example:

class ObjectReturningTagLib {
        static namespace = "cms"
        static returnObjectForTags = ['content']

        def content = { attrs, body ->
                CmsContent.findByCode(attrs.code)?.content
    }
}

Given this example cms.content(code: 'something') call in another taglib or GSP expression would return the value CmsContent.content directly to the caller without wrapping the return value in a buffer. It might be worth doing so also because of performance optimization reasons. There is no need to wrap the tag return value in an output buffer in such cases.

8.3 Fields Plugin

The Fields plugin allows you to customize the rendering of input fields for properties of domain objects, command beans and POGOs based on their type, name, etc. The plugin aims to:

  • Use good defaults for fields.

  • Make it very easy to override the field rendering for particular properties or property types without having to replace entire form templates.

  • Not require you to copy and paste markup for containers, labels and error messages just because you need a different input type.

  • Support inputs for property paths of arbitrary depth and with indexing.

  • Enable other plugins to provide field rendering for special property types that gets picked up automatically (e.g. the Joda Time plugin can provide templates for the various date/time types).

  • Support embedded properties of GORM domain classes.

8.3.1 Installation

The plugin is available on Maven Central and should be a dependency like this:

dependencies {
    implementation 'org.apache.grails:grails-fields:7.0.0-SNAPSHOT'
}

8.3.2 Usage

The plugin provides a set of tags you can use to render the fields in a form.

In the simplest case you can use f:all to render a field for every property of a bean (the domain object or command the form will bind to):

<g:form…>
    <f:all bean="person"/>
</g:form>

To render individual fields you use the f:field tag:

<g:form…>
    <f:field bean="person" property="name"/>
    <f:field bean="person" property="address"/>
    <f:field bean="person" property="dateOfBirth"/>
</g:form>

The f:field tag will automatically handle embedded domain properties recursively:

<f:field bean="person" property="address"/>

If there is no bean object backing a form but you still want to render the surrounding field markup you can give f:field a body:

<f:field property="password">
    <g:password name="password"/>
</f:field>

It should be an unusual case but to render just the widget without its surrounding container you can use the f:widget tag:

<f:widget bean="person" property="name"/>

To make it more convenient when rendering lots of properties of the same bean you can use the f:with tag to avoid having to specify bean on any tags nested inside:

<g:form…>
    <f:with bean="person">
        <f:field property="name"/>
        <f:field property="address"/>
        <f:field property="dateOfBirth"/>
    </f:with>
</g:form>

If you need to render a property for display purposes you can use f:display. It will internally use g:fieldValue, g:formatBoolean or g:formatDate to format the value.

<f:display bean="person" property="name"/>

If you need to render the value in a different way you can give f:display a body instead.

<f:display bean="person" property="dateOfBirth">
    <g:formatDate format="dd MMM yyyy" date="${value}"/>
</f:display>

By default f:display simply renders the property value but if you supply a \_display.gsp template you can render the value in some structured markup, e.g. a table cell or list item. See the Customizing Field Rendering section for how to override templates. For example to render values in a definition list you could use a template like this:

<dt>${label}</dt>
<dd>${value}</dd>

Extra attributes (Since version 2.1.4)

You can pass any number of extra attributes to the f:with and f:all tags that will be propagated to the inner fields and displays. See their individual tags sections for more information.

Breaking changes

Templates

The names of the templates were changed for more adequate ones:

  • _field to _wrapper

  • _input to _widget

  • _display to _displayWrapper

  • _displayWidget was added

To use the old names (for backwards compatibility), configure the following in Config.groovy

grails.plugin.fields.wrapper = "field"
grails.plugin.fields.displayWrapper = "display"
grails.plugin.fields.widget = "input"

Widget attributes

To pass additional attributes to widgets, prefix them with 'widget-'.

Example:

<f:field property="birthDate" widget-format="dd/MM/yyyy"/>

To use the old prefix (for backwards compatibility), configure the following in Config.groovy:

grails.plugin.fields.widgetPrefix = "input-"

Changes in tags

  • The f:input tag was deprecated because the name was confusing. Use the new f:widget tag instead.

  • The f:displayWidget tag was added. It outputs the widget for display purposes, without the wrapper (similar to the widget tag).

Localized numbers

All numbers are now rendered localized. This means that when using Locale.ENGLISH the number 1000.50 is represented as 1,000.50 but with Locale.GERMAN is represented as 1.000,50. To use the old behavior (for backwards compatibility) without localizing the numbers, configure the following in Config.groovy:

grails.plugin.fields.localizeNumbers = false

8.3.3 Customizing Field Rendering

The plugin resolves the GSP template used for each property according to conventions. You can override the rendering based on the class and property name or the property type. The f:field tag looks for a template called _wrapper.gsp, the f:widget tag looks for a template called _widget.gsp, the f:display tag looks for a template called _displayWrapper.gsp.

Breaking changes in version 1.5

In version 1.5 a new template was introduced _displayWidget.gsp. This is the corollary of _widget.gsp for fields that are read-only, i.e. it is responsible for rendering just the markup for the field itself. Furthermore, the default names of all the templates were changed in this version, in the interest of clarity and consistency. The changes to the template names are summarized below:

Table 1. Template Name Changes
Old Template Name (before v.1.5) New Template Name (v.1.5 onwards)

_field.gsp

_wrapper.gsp

_display.gsp

_displayWrapper.gsp

N/A

_displayWidget.gsp

Users upgrading to 1.5 from a previous version should either rename their templates (recommended) or add the following to grails-app/conf/application.yml to change the default templates names to the old names

grails:
    plugin:
        fields:
            wrapper: field
            displayWrapper: display
            widget: input
            displayWidget: displayWidget

Locating Field Templates by Convention

The template for a field is chosen by a convention using the names of the controller, action, bean class, bean property, theme, etc. All the tags will look for templates in the following directories in decreasing order of preference:

  • grails-app/views/controllerNamespace/controllerName/actionName/propertyName/_themes/themeName/

  • grails-app/views/controllerNamespace/controllerName/actionName/_themes/themeName/propertyType/

  • grails-app/views/controllerNamespace/controllerName/actionName/_themes/themeName/

  • grails-app/views/controllerNamespace/controllerName/propertyName/_themes/themeName/

  • grails-app/views/controllerNamespace/controllerName/_themes/themeName/propertyType/

  • grails-app/views/controllerNamespace/controllerName/_themes/themeName/

  • grails-app/views/controllerName/actionName/propertyName/_themes/themeName/

  • grails-app/views/controllerName/actionName/_themes/themeName/propertyType/

  • grails-app/views/controllerName/actionName/_themes/themeName/

  • grails-app/views/controllerName/propertyName/_themes/themeName/

  • grails-app/views/controllerName/_themes/themeName/propertyType/

  • grails-app/views/controllerName/_themes/themeName/

  • grails-app/views/_fields/_themes/themeName/class/propertyName/

  • grails-app/views/_fields/_themes/themeName/superclass/propertyName/

  • grails-app/views/_fields/_themes/themeName/associationType/

  • grails-app/views/_fields/_themes/themeName/propertyType/

  • grails-app/views/_fields/_themes/themeName/propertySuperclass/

  • grails-app/views/_fields/_themes/themeName/default/

  • grails-app/views/controllerNamespace/controllerName/actionName/propertyName/

  • grails-app/views/controllerNamespace/controllerName/actionName/propertyType/

  • grails-app/views/controllerNamespace/controllerName/actionName/

  • grails-app/views/controllerNamespace/controllerName/propertyName/

  • grails-app/views/controllerNamespace/controllerName/propertyType/

  • grails-app/views/controllerNamespace/controllerName/

  • grails-app/views/controllerName/actionName/propertyName/

  • grails-app/views/controllerName/actionName/propertyType/

  • grails-app/views/controllerName/actionName/

  • grails-app/views/controllerName/propertyName/

  • grails-app/views/controllerName/propertyType/

  • grails-app/views/controllerName/

  • grails-app/views/_fields/class/propertyName/

  • grails-app/views/_fields/superclass/propertyName/

  • grails-app/views/_fields/associationType/

  • grails-app/views/_fields/propertyType/

  • grails-app/views/_fields/propertySuperclass/

  • grails-app/views/_fields/default/

The variables referenced in these paths are:

Table 2. Referenced Variables
Name Description

controllerName

The name of the current controller (if any).

actionName

The name of the current action (if any).

themeName

Theme name specified as value of theme attribute (Optional).

class

The bean class. For simple properties this is the class of the object passed to the bean attribute of the f:field or f:widget tag but when the property attribute was nested this is the class at the end of the chain. For example, if the property path was employees[0].address.street this will be the class of address.

superclass

Any superclass or interface of class excluding Object, GroovyObject, Serializable, Comparable and Cloneable and those from GORM.

propertyName

The property name at the end of the chain passed to the property attribute of the f:field or f:widget tag. For example, if the property path was employees[0].address.street then this will be street.

propertyType

The type of the property at the end of the chain passed to the property attribute of the f:field or f:widget tag. For example, for a java.lang.String property this would be string.

propertySuperclass

Any superclass or interface of propertyType excluding Object, GroovyObject, Serializable, Comparable and Cloneable.

associationType

One of 'oneToOne', 'oneToMany', 'manyToMany' or 'manyToOne'. Only relevant if the property is a domain class association.

All class names are camel-cased simple forms. For example java.lang.String becomes string, and com.project.HomeAddress becomes homeAddress.

Templates are resolved in this order so that you can override in the more specific circumstance and fall back to successively more general defaults. For example, you can define a field template for all java.lang.String properties but override a specific property of a particular class to use more specialized rendering.

Templates in plugins are resolved as well. This means plugins such as Joda Time can provide default rendering for special property types. A template in your application will take precedence over a template in a plugin at the same 'level'. For example if a plugin provides a grails-app/views/_fields/string/_widget.gsp the same template in your application will override it but if the plugin provides grails-app/views/_fields/person/name/_widget.gsp it would be used in preference to the more general template in your application.

For most properties the out-of-the-box defaults should provide a good starting point.

Locating Templates Conventionally Example

Imagine an object of class Employee that extends the class Person and has a String name property.

You can override the template f:field uses with any of these:

  • grails-app/views/controllerName/actionName/name/_themes/themeName/_wrapper.gsp

  • grails-app/views/controllerName/actionName/name/_wrapper.gsp

  • grails-app/views/controllerName/actionName/string/_wrapper.gsp

  • grails-app/views/controllerName/actionName/_wrapper.gsp

  • grails-app/views/controllerName/name/_wrapper.gsp

  • grails-app/views/controllerName/string/_wrapper.gsp

  • grails-app/views/controllerName/_wrapper.gsp

  • grails-app/views/_fields/employee/name/_wrapper.gsp

  • grails-app/views/_fields/person/name/_wrapper.gsp

  • grails-app/views/_fields/string/_wrapper.gsp

  • grails-app/views/_fields/default/_wrapper.gsp

override the template f:widget uses with any of these:

  • grails-app/views/controllerName/actionName/name/_themes/themeName/_widget.gsp

  • grails-app/views/controllerName/actionName/name/_widget.gsp

  • grails-app/views/controllerName/actionName/string/_widget.gsp

  • grails-app/views/controllerName/actionName/_widget.gsp

  • grails-app/views/controllerName/name/_widget.gsp

  • grails-app/views/controllerName/string/_widget.gsp

  • grails-app/views/controllerName/_widget.gsp

  • grails-app/views/_fields/employee/name/_widget.gsp

  • grails-app/views/_fields/person/name/_widget.gsp

  • grails-app/views/_fields/string/_widget.gsp

  • grails-app/views/_fields/default/_widget.gsp

And override the template f:display uses with any of these:

  • grails-app/views/controllerName/actionName/name/_themes/themeName/_displayWrapper.gsp

  • grails-app/views/controllerName/actionName/name/_displayWrapper.gsp

  • grails-app/views/controllerName/actionName/string/_displayWrapper.gsp

  • grails-app/views/controllerName/actionName/_displayWrapper.gsp

  • grails-app/views/controllerName/name/_displayWrapper.gsp

  • grails-app/views/controllerName/string/_displayWrapper.gsp

  • grails-app/views/controllerName/_displayWrapper.gsp

  • grails-app/views/_fields/employee/name/_displayWrapper.gsp

  • grails-app/views/_fields/person/name/_displayWrapper.gsp

  • grails-app/views/_fields/string/_displayWrapper.gsp

  • grails-app/views/_fields/default/_displayWrapper.gsp

During template development it is usually recommended to disable template caching in order to allow the plugin to recognize new/renamed/moved templates without restarting the application. See the "Performance" section of the guide for the exact settings.

See Template Seach Path

The plugin logs which locations it is checking for templates as debug log. You can enable this by defining a logger in logback.groovy

logger('grails.plugin.formfields.FormFieldsTemplateService', DEBUG,['STDOUT'])

The can disable the caching in application.yml using:

grails:
    plugin:
        fields:
            disableLookupCache: true

Default Behaviour - Using Grails Widget Tags

If no template override is found the plugin will use the standard grails input tags (e.g. g:select, g:checkbox, g:field) for rendering input controls. Using f:field you can pass extra arguments (e.g. optionKey, optionValue) through to these tags by prefixing them with widget-, e.g.

<f:field bean="person" property="gender" widget-optionValue="name"/>

Template parameters

The f:field and f:widget tags will pass the following parameters to your templates or to the body of f:field if you use one:

Table 3. Template Parameters
Name Type Description

bean

Object

The bean attribute as passed to the f:field or f:widget tag.

property

String

The property attribute as passed to the f:field or f:widget tag. This would generally be useful for the name attribute of a form input.

type

Class

The property type.

label

String

The field label text. This is based on the label attribute passed to the f:field or f:widget tag. If no label attribute was used the label is resolved by convention - see below.

value

Object

the property value. This can also be overridden or defaulted if the value or default attribute was passed to f:field or f:widget.

constraints

ConstrainedProperty

The constraints for the property if the bean is a domain or command object.

persistentProperty

DomainProperty

The persistent property object if the bean is a domain object.

errors

List<String>

The error messages for any field errors present on the property. If there are no errors this will be an empty List.

required

boolean

true if the field is required, i.e. has a nullable: false or blank: false constraint.

invalid

boolean

true if the property has any field errors.

prefix

String

A string (including the trailing period) that should be appended before the input name such as name="${prefix}propertyName". The label is also modified.

In addition f:field passes the following parameters:

Table 4. Parameter Names from f:field

Name

Type

Description

widget

String

The output of f:widget for the current bean and property if f:field was used without a tag body, otherwise the output of the tag body.

If the bean attribute was not supplied to f:field then bean, type, value and persistentProperty will all be null.

Field labels

If the label attribute is not supplied to the f:field tag then the label string passed to the field template is resolved by convention. The plugin uses the following order of preference for the label:

  • An i18n message using the key 'beanClass.path.label'. For example when using <f:field bean="authorInstance" property="book.title"/> the plugin will try the i18n key author.book.title.label. If the property path contains any index it is removed so <f:field bean="authorInstance" property="books[0].title"/> would use the key author.books.title.label.

  • For classes using the same bean class as properties, it is possible to get a key without the class name prefixed. If the configuration value grails.plugin.fields.i18n.addPathFromRoot is set to true (default: false). Example: a class Publisher has two Address properties authorAddress and printAddress. With addPathFromRoot=true they will share the key address.city.label. The same goes if Author and Publisher had a Book book, the key would be book.title.label, and if they both had a List<Book> books the key would be books.title.label

  • An i18n message using the key 'objectType.propertyName`.label’. For example when using <f:field bean="personInstance" property="address.city"/> the plugin will try the i18n key address.city.label.

  • The natural property name. For example when using <f:field bean="personInstance" property="dateOfBirth"/> the plugin will use the label "Date Of Birth".

Locating Field Templates Directly

Rather than relying on the convention described previously to locate the template(s) to be used for a particular field, it is instead possible to directly specify the directory containing the templates. This feature was introduced in version 1.5.

  • The wrapper attribute can be used with the f:field or f:display tags to specify the directory containing the _wrapper.gsp or _displayWrapper.gsp template to be used

  • The widget attribute can be used with the f:field or f:display tags to specify the directory containing the _widget.gsp or _displayWidget.gsp template to be used

  • If the wrapper and widget templates both have the same value, the templates attribute can be used instead as a shorthand. For example:

<f:field property="startDate" templates="bootstrap3" />

is equivalent to:

<f:field property="startDate" wrapper="bootstrap3" widget="bootstrap3" />

if theme is specified, theme will be searched first to find the templates For example

<f:field property="startDate" templates="custom" theme="bs-horizontal"/>

Will search the templates first in \_fields/_themes/bs-horizontal/custom and then \_fields/custom

If a direct location is specified, and the templates cannot be found therein, the plugin will fall back to locating templates by convention.

Locating Templates Directly Example

// renders _fields/\_themes/bs-horizontal/custom/_wrapper.gsp:
<f:field property="startDate" wrapper="custom" theme="bs-horizontal"/>

// renders _fields/bootstrap3/_wrapper.gsp:
<f:field property="startDate" wrapper="bootstrap3"/>

// renders _fields/time/_widget.gsp:
<f:field property="startDate" widget="time"/>

// renders _fields/time/_wrapper.gsp and _fields/time/_widget.gsp:
<f:field property="startDate" templates="time"/>

// renders _fields/\_themes/bs-horizontal/custom/_displayWrapper.gsp:
<f:display property="startDate" wrapper="custom" theme="bs-horizontal"/>


// renders _fields/bootstrap3/_displayWrapper.gsp:
<f:display property="startDate" wrapper="bootstrap3"/>

// renders _fields/time/_displayWidget.gsp:
<f:display property="startDate" widget="time"/>

// renders _fields/time/_displayWrapper.gsp and _fields/time/_displayWidget.gsp:
<f:display property="startDate" templates="time"/>

8.3.4 Embedded Properties

Embedded properties are handled in a special way by the f:field and f:all tags. If the property attribute you pass to f:field is an embedded property then the tag recursively renders each individual property of the embedded class with a surrounding fieldset. For example if you have a Person class with a name property and an Address embedded class with street, city and country properties <f:field bean="person" property="address"> will effectively do this:

<fieldset class="embedded address">
    <legend>Address</legend>
    <f:field bean="person" property="address.street"/>
    <f:field bean="person" property="address.city"/>
    <f:field bean="person" property="address.country"/>
</fieldset>

You can customize how embedded properties are surrounded by providing a layout at grails-app/views/layouts/_fields/embedded.gsp which will override the default layout provided by the plugin.

When you use the f:all tag it will automatically handle embedded properties in this way.

8.3.5 Themes

Since version 2.1.4 It is possible to create themes to provide set of templates for different css frameworks or form layouts. For example, a bootstrap-fields plugin can provide different themes (eg bs-horizontal, bs-vertical) to support horizontal and vertical form layouts. And another plugin can provide theme for purecss framework.

Themes are put under directory _fields/themes/themeName/.

All of the field tags supports theme attribute which accepts the name of the theme. When a theme name is specified, widget, wrapper, and display templates will be searched in theme directory first as described in Customizing Field Rendering.

8.3.6 Including Templates in Plugins

Plugins can include field and/or input level templates to support special UI rendering or non-standard property types. Just include the templates in the plugin’s grails-app/views directory as described in the Customizing Field Rendering section.

If you supply templates in a plugin you should consider declaring a <%@page defaultCodec="html" %> directive so that any HTML unsafe property values are escaped properly regardless of the default codec used by client apps.

In order to be performant, the Fields plugin caches field template lookup results by default. This makes it possible to perform the time-consuming template path resolutions only once during the runtime of the application.

When template caching is active, only the first page renderings are slow, subsequent ones are fast.

Due to the flexibility needed during template development, this feature can be disabled so it would be possible to recognize newly added field templates without restarting the application. As a result, with bigger webpages, containing a lot of fields, rendering may be fairly slow in development (depending on the number of fields on the page).

8.3.7 Performance

For template development, the following configuration attribute should be placed in the development environment section of your application’s Config.groovy:

application.groovy
grails.plugin.fields.disableLookupCache = true

or

application.yml
environments:
    development:
        grails:
            plugin:
                fields:
                    disableLookupCache: true

After the template development has finished, it is recommended to re-enable the template lookup cache in order to have a performant page rendering even during development.

8.3.8 Scaffolding

Scaffolding templates based on the Fields plugin are quite powerful as they will pick up field and input rendering templates from your application and any plugins that provide them. This means that the useful life of scaffolding templates should be much longer as you do not need to replace the entire create.gsp and/or edit.gsp template just because you want to do something different with a certain property of one particular class.

The plugin makes the renderEditor.template file used by standard Grails scaffolding redundant. This template was very limited because it could not be extended by plugins or applications (only replaced) and was unable to support embedded properties of domain classes.

The Fields plugin includes scaffolding templates you can use in your application by running:

grails install-form-fields-templates

This will overwrite any create.gsp and edit.gsp files you have in src/templates/scaffolding.

Alternatively, it’s very easy to modify your existing scaffolding templates to use the f:all tag or multiple f:field tags.

8.4 JSON Views

JSON views are written in Groovy, end with the file extension gson and reside in the grails-app/views directory. They allow rendering of JSON responses using Groovy’s StreamingJsonBuilder by providing a DSL for producing output in the JSON format. A hello world example can be seen below:

grails-app/views/hello.gson
json.message {
    hello "world"
}

The above JSON view results in the output:

{"message":{ "hello":"world"}}

The json variable is an instance of StreamingJsonBuilder. See the documentation in the Groovy user guide for more information on StreamingJsonBuilder.

More example usages:

json(1,2,3) == "[1,2,3]"
json { name "Bob" } == '{"name":"Bob"}'
json([1,2,3]) { n it } == '[{"n":1},{"n":2},{"n":3}]'

You can specify a model to view in one of two ways. Either with a model block:

grails-app/views/hello.gson
model {
    String message
}
json.message {
    hello message
}

Or with the @Field transformation provided by Groovy:

grails-app/views/hello.gson
import groovy.transform.Field
@Field String message
json.message {
    hello message
}

8.4.1 Installation

To activate JSON views, add the following dependency to the dependencies block of your build.gradle:

compile "org.apache.grails:grails-views-gson:7.0.0-SNAPSHOT"

To enable Gradle compilation of JSON views for production environment add the following to the buildscript dependencies block:

buildscript {
    ...
    dependencies {
        ...
        classpath "org.apache.grails:grails-gradle-bom:7.0.0-SNAPSHOT"
        classpath "org.apache.grails:grails-gradle-plugins"
    }
}

Then apply the org.apache.grails.grails-views-gson Gradle plugin after any Grails core gradle plugins:

...
apply plugin: "org.apache.grails:grails-web"
apply plugin: "org.apache.grails.grails-views-gson"

This will add a compileGsonViews task to Gradle that is executed when producing a JAR or WAR file.

8.4.2 Templates

Template Basics

You can define templates starting with underscore _. For example given the following template called _person.gson:

grails-app/views/person/_person.gson
model {
    Person person
}
json {
    name person.name
    age person.age
}

You can render the template with the g.render method:

grails-app/views/person/show.gson
model {
    Person person
}
json g.render(template:"person", model:[person:person])

The above assumes the view is in the same directory as the template. If this is not the case you may need to use a relative URI to the template:

grails-app/views/family/show.gson
model {
    Person person
}
json g.render(template:"/person/person", model:[person:person])

Template Namespace

The previous example can be simplified using the template namespace:

grails-app/views/person/show.gson
model {
    Person person
}
json tmpl.person(person)

In this example, the name of the method call (person in this case) is used to dictate which template to render.

The argument to the template becomes the model. The name of the model variable is the same as the template name. If you wish to alter this you can pass a map instead:

grails-app/views/person/show.gson
model {
    Person person
}
json tmpl.person(individual:person)

In the above example the model variable passed to the _person.gson template is called individual.

This technique may also be used when you want to render a template using a relative path:

grails-app/views/person/show.gson
model {
    Person person
}
json tmpl.'/person/person'(person:person)

The template namespace even accepts a collection (or any Iterable object):

grails-app/views/person/show.gson
model {
    List<Person> people = []
}
json tmpl.person(people)

In this case the output is a JSON array. For example:

    [{"name":"Fred",age:10},{"name":"Bob",age:12}]

When rendering an Iterable, you can also specify the model name:

grails-app/views/person/show.gson
model {
    List<Person> people = []
}
json tmpl.person("owner", people)

The person template would have a field defined: Person owner

If you need additional data that will be static over each iteration of the template, you can also pass in a model:

grails-app/views/person/show.gson
model {
    List<Person> people = []
}
json tmpl.person(people, [relationship: "Father"])

The person template could have a field defined: String relationship

By passing in a collection the plugin will iterate over each element on the collection and render the template as a JSON array. If you do not want this to happen then use the variation of the method that takes a map instead:

grails-app/views/person/show.gson
model {
    List<Person> people = []
}
json tmpl.person(people:people)

More Ways to Render Templates

The g.render method is flexible, you can render templates in many forms:

model {
    Family family
}
json {
    name family.father.name
    age family.father.age
    oldestChild g.render(template:"person", model:[person: family.children.max { Person p -> p.age } ])
    children g.render(template:"person", collection: family.children, var:'person')
}

However, most of these use cases are more concise with the template namespace:

model {
    Family family
}
json {
    name family.father.name
    age family.father.age
    oldestChild tmpl.person( family.children.max { Person p -> p.age } ] )
    children tmpl.person( family.children )
}

Template Inheritance

JSON templates can inherit from a parent template. For example consider the following parent template:

grails-app/views/_parent.gson
model {
    Object object
}
json {
    hal.links(object)
    version "1.0"
}

A child template can inherit from the above template by using the inherits method:

grails-app/views/_person.gson
inherits template:"parent"
model {
    Person person
}
json {
    name person.name
}

The JSON from the parent and the child template will be combined so that the output is:

 {
   "_links": {
     "self": {
       "href": "http://localhost:8080/person/1",
       "hreflang": "en",
       "type": "application/hal+json"
     }
   },
   "version": "1.0",
   "name": "Fred"
 }

The parent template’s model will be formulated from the child templates model and the super class name. For example if the model is Person person where Person extends from Object then the final model passed to the parent template will look like:

[person:person, object:person]

If the Person class extended from a class called Mammal then the model passed to the parent would be:

[person:person, mammal:person]

This allows you to design your templates around object inheritance.

You can customize the model passed to the parent template using the model argument:

inherits template:"parent", model:[person:person]

8.4.3 Rendering Domain Classes

Basics of Domain Class Rendering

Typically your model may involve one or many domain instances. JSON views provide a render method for rendering these.

For example given the following domain class:

class Book {
    String title
}

And the following template:

model {
    Book book
}
json g.render(book)

The resulting output is:

{"id":1,"title":"The Stand"}

You can customize the rendering by including or excluding properties:

json g.render(book, [includes:['title']])

Or by providing a closure to provide additional JSON output:

json g.render(book) {
    pages 1000
}

Or combine the two approaches:

json g.render(book, [includes:['title']]) {
    pages 1000
}

Deep Rendering of Domain Classes

Typically the g.render(..) method will only render objects one level deep. In other words if you have a domain class such as:

class Book {
    String title
    Author author
}

The resulting output will be something like:

{"id":1,"title":"The Stand","author":{id:1}}

If you wish for the author to be included as part of the rendering, there are two requirements, first you must make sure the association is initialized.

If the render method encounters a proxy, it will not traverse into the relationship to avoid N+1 query performance problems.

The same applies to one-to-many collection associations. If the association has not been initialized the render method will not traverse through the collection!

So you must make sure your query uses a join:

Book.findByTitle("The Stand", [fetch:[author:"join"]])

Secondly when calling the render method you should pass the deep argument:

json g.render(book, [deep:true])

Alternatively, to only expand a single association you can use the expand argument:

json g.render(book, [expand:['author']])
request parameters can also be used to expand associations (eg. ?expand=author), if you do not want to allow this, then use includes or excludes to include only the properties you want.

Finally, if you prefer to handle the rendering yourself you can do by excluding the property:

json g.render(book, [excludes:['author']]) {
    author {
        name book.author.name
    }
}

Domain Class Rendering and Templates

An alternative to the default behaviour of the render method is to rely on templates.

In other words if you create a /author/_author.gson template and then use the g.render method on an instance of book:

json g.render(book)

Whenever the author association is encountered the g.render method will automatically render the /author/_author.gson template instead.

8.4.4 JSON View API

All JSON views subclass the JsonViewTemplate class by default.

The JsonViewTemplate superclass implements the JsonView trait which in turn extends the the GrailsView trait.

Thanks to these traits several methods and properties are available to JSON views that can be used to accomplish different tasks.

Links can be generated using the g.link(..) method:

json.person {
    name "bob"
    homepage g.link(controller:"person", id:"bob")
}

The g.link method is similar to the equivalent tag in GSP and allows you to easily create links to other controllers.

Altering the Response Headers

To customize content types and headers use the response object defined by the HttpView trait:

response.contentType "application/hal+json"
response.header "Token", "foo"
json.person {
    name "bob"
}

The HttpView trait defines a variety of methods for inspecting the request and altering the response.

The methods available are only a subset of the methods available via the HttpServletRequest and HttpServletResponse objects, this is by design as view logic should be limited and logic performed in the controller instead.

Accessing the Request

Various aspects of the request can be accessed by the request object defined by the HttpView trait:

json.person {
 name "bob"
 userAgent request.getHeader('User-Agent')
}

Parameters can be accessed via the params object which is an instance of Parameters:

json.person {
 name "bob"
 first params.int('offset', 0)
 sort params.get('sort', 'name')
}

Default Static Imports

The following classes' static properties are imported by default:

  • org.springframework.http.HttpStatus

  • org.springframework.http.HttpMethod

  • grails.web.http.HttpHeaders

This means that you can use the response object to set the status using these constants, instead of hard coded numbers:

response.status NOT_FOUND

Or generate links using the appropriate HTTP method:

g.link(resource:"books", method:POST)

I18n & Locale Integration

You can lookup i18n messages use the g.message method:

json.error {
    description g.message(code:'default.error.message')
}

You can also create locale specific views by appending the locale to view name. For example person_de.gson for German or person.gson for the default.

For more complex message lookups the messageSource property is an instance of the Spring MessageSource class.

Accessing Configuration

The application configuration is injected automatically into your json views. To access it, simply reference config.

json {
    foo config.getProperty("bar", String, null)
}

Miscellaneous Properties

Other properties are also available:

controllerName

The name of the current controller

actionName

The name of the current controller action

controllerNamespace

The namespace of the current controller

8.4.5 Model Naming

Grails Framework supports a convention for the model names in your JSON views. If the convention does not meet your needs, model variables can be explicitly defined.

Some model names are reserved since there are properties of the same name injected into the view: locale, response, request, page, controllerNamespace, controllerName, actionName, config, generator, json

Explicit Model Naming

Given a view:

grails-app/views/hello/index.gson
model {
    String message
}
json.message {
    hello message
}

Then the controller has to specify the name to be used in the view:

grails-app/controllers/HelloController.groovy
def index() {
    respond(message: "Hello World")
    //or [message: "Hello World"]
}

When using a template:

grails-app/views/hello/_msg.gson
model {
    String message
}
json.message {
    hello message
}

In the view you can use the tmpl namespace:

json {
    message tmpl.msg([message: message])
    // or g.render(template:'msg', model:[message: message])
    // or g.render(template:'msg', model: message, var:'message')
}

Using collections:

model {
    List<String> messages
}
json {
    messages tmpl.msg('message', messages)
    // or g.render(template:'msg', collection: messages, var: 'message')
}

Model By Convention

Property Type

When rendering a non iterable object, the property name of the type is used when a name is not specified.

grails-app/views/hello/index.gson
model {
    String string
}
json.message {
    hello string
}

The variable can be passed in directly to respond.

grails-app/controllers/HelloController.groovy
def index() {
    respond("Hello World")
}

This also applies when rendering templates with tmpl.

grails-app/views/hello/_msg.gson
model {
    String string
}
json.message {
    hello string
}
grails-app/views/hello/index.gson
model {
    String someString
}
json tmpl.msg(someString)

If a collection is rendered, the property name of the component type is appended with the property name of the collection type. The component type is based on the first item in the list.

List<String>stringList

Set<String>stringSet

Bag<String>stringCollection

If the collection is empty, emptyCollection will be used as the default model name. This is due to not being able to inspect the first object’s type.

grails-app/views/hello/index.gson
model {
    String stringList
}
json {
    strings stringList
}

The variable can be passed in directly to respond.

grails-app/controllers/HelloController.groovy
def index() {
    respond(["Hello", "World"])
}
The component+collection convention does not apply when rendering collections with tmpl inside a view.

Template Name

When using a template, unless specified, the model name is based on the template name.

Given the following template:

grails-app/views/hello/_msg.gson
model {
    String msg // or String string
}
json.message {
    hello msg
}

To render a single message from another view using the template:

grails-app/views/hello/index.gson
json.message tmpl.msg(message)

To render a collection of messages from another view using the template:

grails-app/views/hello/index.gson
model {
    List<String> stringList
}
json {
    messages tmpl.msg(stringList)
}

In both cases the convention of the variable name matching the template name is used.

8.4.6 Content Negotiation

GSON views integrate with Grails' content negotiation infrastructure. For example if you create two views called grails-app/views/book/show/show.gsp (for HTML) and grails-app/views/book/show/show.gson (for JSON), you can then define the following action:

grails-app/controllers/myapp/BookController.groovy
def show() {
    respond Book.get(params.id)
}

The result is that if you send a request to /book/show it will render show.gsp but if you send a request to /book/show.json it will render show.gson.

In addition, if the client sends a request with the Accept header containing application/json the show.gson view will be rendered.

Content Negotiation and Domain Classes

Content negotiation also works nicely with domain classes, for example if you want to define a template to render any instance of the Book domain class you can create a gson file that matches the class name.

For example given a class called demo.Book you can create grails-app/views/book/_book.gson and whenever respond is called with an instance of Book Grails will render _book.gson.

def show() {
    respond Book.get(params.id)
}

If you define an index action that responds with a list of books:

def index() {
    respond Book.list()
}

Then you can create a corresponding grails-app/views/book/index.gson file that renders each book:

grails-app/views/book/index.gson
@Field List<Book> bookList

json tmpl.book(bookList)
When responding with a list of objects Grails automatically appends the suffix "List" to the model name, so in this case the model name is bookList

By calling the tmpl.book(..) method with the list of books the grails-app/views/book/_book.gson template will be rendered for each one and a JSON array returned.

Global Default Template

You can also define a /object/_object template that is rendered by default if no other template is found during content negotiation. To do this create a file called /grails-app/views/object/_object.gson where the name of the model is object, for example:

model {
    Object object
}
json g.render(object)

Content Negotiation and Versioned APIs

A typical use case when building REST APIs is the requirement to support different versions of the API. GSON views can be versioned by including the version in the name of the view.

Grails will then use the ACCEPT-VERSION header when resolving the view.

For example given a view called /book/show.gson if you wish to deprecate your previous API and create a version 2.0 API, you can rename the previous view /book/show_v1.0.gson and create a new /book/show.gson representing the new version of the API.

Then when the client sends a request with the ACCEPT-VERSION header containing v1.0 the /book/show_v1.0.gson view will be rendered instead of /book/show.gson.

Content Negotiation and View Resolving Strategy

Grails Framework takes into account a number of factors when attempting to resolve the view including the content type, version and locale.

The paths searched are following:

  • view_name[_LOCALE][_ACCEPT_CONTENT_TYPE][_ACCEPT-VERSION].gson (Example: show_de_hal_v1.0.gson)

  • view_name[_LOCALE][_ACCEPT_CONTENT_TYPE].gson (Example: show_de_hal.gson)

  • view_name[_LOCALE][_ACCEPT-VERSION].gson (Example: show_de_v1.0.gson)

  • view_name[_LOCALE].gson (Example: show_de.gson)

  • view_name[_ACCEPT_CONTENT_TYPE][_ACCEPT-VERSION].gson (Example: show_hal_v1.0.gson)

  • view_name[_ACCEPT-VERSION][_ACCEPT_CONTENT_TYPE].gson (Example: show_v1.0_hal.gson)

  • view_name[_ACCEPT_CONTENT_TYPE].gson (Example: show_hal.gson)

  • view_name[_ACCEPT-VERSION].gson (Example: show_v1.0.gson)

  • view_name.gson (Example: show.gson)

The content type (defined by either the ACCEPT header or file extension in the URI) is taken into account to allow different formats for the same view.

Content Negotiation and Custom Mime Types

Some REST APIs use the notion of custom mime types to represent resources. Within Grails you can for example define custom mime types in grails-app/conf/application.yml:

grails:
    mime:
        types:
            all:      "*/*"
            book:     "application/vnd.books.org.book+json"
            bookList: "application/vnd.books.org.booklist+json"

Once these custom mime types have been defined you can then define a view such as show.book.gson for that particular mime type.

8.4.7 HAL Support

HAL is a standard format for representing JSON that has gained traction for its ability to represent links between resources and provide navigable APIs.

The JSON views plugin for Grails provides HAL support out-of-the-box. All JSON views have access to the hal instance which implements HalViewHelper.

For example:

model {
    Book book
}
json {
    hal.links(book)
    hal.embedded {
        author( book.authors.first() ) { Author author ->
            name author.name
        }
    }
    title book.title
}
The call to hal.links() has to be the first element within the json{} closure.

This produces the HAL output:

{
    "_links": {
        "self": {
            "href": "http://localhost:8080/book/show/1",
            "hreflang": "en",
            "type": "application/hal+json"
        }
    },
    "_embedded": {
        "author": {
            "_links": {
                "self": {
                    "href": "http://localhost:8080/author/show/1",
                    "hreflang": "en",
                    "type": "application/hal+json"
                }
            },
            "name": "Stephen King"
        }
    },
    "title": "The Stand"
}

The above example uses the hal.links(..) method to render links for a domain resource and the hal.embedded(..) method to define any embedded objects that form part of the HAL response.

The hal.links(..) method will by default create a link to the resource, but you can define additional links by annotating the domain class with either grails.rest.Linkable or grails.rest.Resource and using the link method on the object:

book.link(rel:"publisher", href:"http://foo.com/books")

The link will then be included in the HAL output.

If you wish to be specific about which links to include you can do so by passing a map of objects to link to:

model {
    Book book
}
json {
    hal.links(self:book, author: book.author)
    ...
}

Alternatively, if you prefer to define the HAL links yourself then you can do so by passing a closure to the hal.links method:

model {
    Book book
}
json {
    hal.links {
        self {
            href '...'
            hreflang 'en'
            type "application/hal+json"
        }
    }
    ...
}

Rendering Domain Classes as HAL

If you prefer to let the plugin handle the rendering of your object you can use the hal.render(..) method:

model {
    Book book
}
json hal.render(book)

The hal.render method works the same as the g.render method, accepting the same arguments, the difference being it will output HAL links for the object via hal.links and also output associations fetched via a join query for hal.embedded.

For example you can also customize the content of the generated HAL with a closure:

model {
    Book book
}
json hal.render(book) {
    pages 1000
}

Embedded Association and HAL

Generally, when using the hal.render(..) method, _embedded associations are only rendered for associations that have been initialized and eagerly fetched. This means that the following query will not render the book.authors association:

Book.get(params.id)

However, this query will render the book.authors association:

Book.get(params.id, [fetch:[authors:'eager']])

This is by design and to prevent unexpected performance degradation due to N+1 query loading. If you wish to force the render method to render _embedded associations for HAL you can do see using the deep argument:

json hal.render(book, [deep:true])

You can prevent HAL _embedded associations from being rendering using the embedded:false parameter:

model {
    Book book
}
json hal.render(book, [embedded:false])

You can also render embedded associations without using the hal.render(..) method, by using the hal.embedded(..) method:

model {
    Book book
}
json {
    hal.embedded(book)
    title book.title
}
Like the hal.links(..) method, the hal.embedded(..) method should come first, before any other attributes, in your JSON output

You can also control which associations should be embedded by using a map argument instead:

model {
    Book book
}
json {
    hal.embedded(authors: book.authors)
    title book.title
}

And you can inline the contents of the book without any associations using the hal.inline(..) method:

model {
    Book book
}
json {
    hal.embedded(authors: book.authors)
    hal.inline(book)
}

To customize the contents of the inlined JSON output use a closure:

model {
    Book book
}
json {
    hal.embedded(authors: book.authors)
    hal.inline(book) {
        pages 300
    }
}
You cannot include additional content after the call to hal.inline(..) as this will produce invalid JSON

You can combine hal.embeddded(..) and hal.links(..) to obtain exactly the links and the embedded content you want:

model {
    Book book
}
json {
    hal.links(self: book )
    hal.embedded(authors: book.authors)
    hal.inline(book) {
        pages 300
    }
}

Specifying the HAL Content Type

The default HAL response content type is application/hal+json, however as discussed in the section on Custom Mime Type you can define your own response content types to represent your resources.

For example given the following configuration in grails-app/conf/application.yml:

grails:
    mime:
        types:
            all:      "*/*"
            book:     "application/vnd.books.org.book+json"

You can set the HAL content type to an explicit content type or one of the named content types defined in grails.mime.types in application.yml:

model {
    Book book
}
hal.type("book")
json {
    ...
}

HAL Pagination

The JSON views plugin for Grails provides navigable pagination support. Like the GSP <g:paginate> tag, the parameters include: total, max, offset, sort and order.

For example:

model {
    Iterable<Book> bookList
    Integer bookCount
    Integer max // optional, defaults to 10
    Integer offset // optional, defaults to 0
    String sort // optional
    String order // optional
}
json {
    hal.paginate(Book, bookCount, max, offset, sort, order)
    ...
}
Similar to hal.links() the hal.paginate() has to be the first element within the json{} closure.

When accessing http://localhost:8080/book?offset=10 this produces the navigable output like:

{
  "_links": {
    "self": {
      "href": "http://localhost:8080/book/index?offset=10&max=10",
      "hreflang": "en_US",
      "type": "application/hal+json"
    },
    "first": {
      "href": "http://localhost:8080/book/index?offset=0&max=10",
      "hreflang": "en_US"
    },
    "prev": {
      "href": "http://localhost:8080/book/index?offset=0&max=10",
      "hreflang": "en_US"
    },
    "next": {
      "href": "http://localhost:8080/book/index?offset=20&max=10",
      "hreflang": "en_US"
    },
    "last": {
      "href": "http://localhost:8080/book/index?offset=40&max=10",
      "hreflang": "en_US"
    }
  },
  ...
}
If there aren’t enough results to paginate the navigation links will not appear, Likewise, the prev and next links are only present when there is a previous or next page.

If you have other links that you want to include along with the pagination links then you can use the hal.links(..) method with pagination arguments:

model {
    Author author
    Iterable<Book> bookList
    Integer bookCount
}
json {
    // the model, type to paginate, and the total count
    hal.links([author:author], Book, bookCount)
    ...
}

8.4.8 JSON API Support

JSON API is a standard format for representing JSON.

The JSON views plugin for Grails provides JSON API support out-of-the-box. All JSON views have access to the jsonapi instance which implements JsonApiViewHelper.

Grails views makes a best effort to conform to the JSON API standard, however that only applies to the format of the data. The specification makes many assertions about response codes, url conventions, and other server related concepts that are overreaching.

The JSON API support in Grails also only applies to domain classes. Because the specification relies on concepts of relationships and identifiers, there is no clear way to determine how those concepts would apply to conventional Groovy classes. As a result, normal Groovy classes are not supported.

The simplest example of using JSON API simply passes a domain class to the render method of the jsonapi object.

For example:

model {
    Book book
}
json jsonapi.render(book)

In the example where Book looks like the following:

class Book {
    String title
    Author author
}

This is what an example Book instance rendered with JSON API might look like.

{
  "data": {
    "type": "book",
    "id": "3",
    "attributes": {
      "title": "The Return of the King"
    },
    "relationships": {
      "author": {
        "links": {
          "self": "/author/9"
        },
        "data": {
          "type": "author",
          "id": "9"
        }
      }
    }
  },
  "links": {
    "self": "http://localhost:8080/book/3"
  }
}

JSON API Object

To include the JSON API Object in the response, include a jsonApiObject argument to the render method.

model {
    Book book
}
json jsonapi.render(book, [jsonApiObject: true])

The response will contain "jsonapi":{"version":"1.0"} as the first key in the resulting object.

Meta Object

To add metadata to your response, the meta argument can be passed to render with the value being the object that should be rendered. If this functionality is used in addition to jsonApiObject: true, the metadata will be rendered as the "meta" property of the "jsonapi" object.

model {
    Book book
}
json jsonapi.render(book, [meta: [name: "Metadata Information"]])

The response will contain "meta":{"name":"Metadata Information"} as the first key in the resulting object.

Rendering Errors

The JSON API specification has instructions on how to render errors. In the case of the Grails implementation, this applies to both exceptions and validation errors.

Exceptions

If an exception is passed to the render method, it will be rendered within the specification.

In the example of an exception new RuntimeException("oops!"), the following will be rendered:

{
  "errors": [
    {
      "status": 500,
      "title": "java.lang.RuntimeException",
      "detail": "oops!",
      "source": {
        "stacktrace": [
          //An array of information relating to the stacktrace
        ]
      }
    }
  ]
}

Validation Errors

In the case of validation errors, the response will look like the following when a name property fails the blank constraint:

{
  "errors": [
    {
      "code": "blank",
      "detail": "Property [name] of class [class com.foo.Bar] cannot be blank",
      "source": {
        "object": "com.foo.Bar",
        "field": "name",
        "rejectedValue": "",
        "bindingError": false
      }
    }
  ]
}

In general, links for relationships will be provided when the relationship has a value.

Example output for a has one relationship where the value is null:

"captain": {
  "data": null
}

And when the value is not null:

"author": {
  "links": {
    "self": "/author/9"
  },
  "data": {
    "type": "author",
    "id": "9"
  }
}

Currently links are not supported in the case of to many relationships.

Pagination

The JSON API specification has a section which explains pagination. The Grails implementation follows that specification as it is written.

To enable pagination links in your output you must be rendering a collection and also include some arguments in addition to the collection being rendered. There are two required arguments: total and resource. The default offset is 0 and max is 10.

model {
    List<Book> books
    Integer bookTotal
}
json jsonapi.render(books, [pagination: [total: bookTotal, resource: Book]])

Example links output if bookTotal == 20:

"links": {
  "self": "/books",
  "first": "http://localhost:8080/books?offset=0&max=10",
  "next": "http://localhost:8080/books?offset=10&max=10",
  "last": "http://localhost:8080/books?offset=10&max=10"
}

By default the values for offset, sort, max, and order will come from the parameters with the same names. You can override their values by passing the corresponding argument in the pagination Map.

model {
    List<Book> books
    Integer bookTotal
}
json jsonapi.render(books, [pagination: [total: bookTotal, resource: Book, max: 20, sort: params.myCustomSortArgument]])

Associations

The JSON API specification details how relationships should be rendered. The first way is through a relationships object described here. By default that is now relationships will be rendered in json views.

If you do not wish to render the relationships at all, the associations argument can be passed to render with the value of false.

model {
    Book book
}
json jsonapi.render(book, [associations: false])

The specification also has a section that describes compound documents. If you want one or more of your relationships to be rendered in that manner, you can include the expand argument.

model {
    Book book
}
json jsonapi.render(book, [expand: "author"]) //can also be a list of strings

Includes / Excludes

The JSON API implementation in Grails supports the same includes and excludes support as normal json views. Please see the section on rendering for details.

Identifier Rendering

Grails provides a way to customize the rendering of your domain class identifiers. To override the default behavior, register a bean that implements JsonApiIdRenderStrategy.

grails-app/conf/spring/resources.groovy
beans = {
    jsonApiIdRenderStrategy(MyCustomImplementation)
}

8.4.9 The JsonTemplateEngine

The JSON Views plugin registers a bean called jsonTemplateEngine of type JsonViewTemplateEngine.

This class is a regular Groovy TemplateEngine, and you can use the engine to render JSON views outside the scope of an HTTP request.

For example:

@Autowired
JsonViewTemplateEngine templateEngine
void myMethod() {
        Template t = templateEngine.resolveTemplate('/book/show')
        def writable = t.make(book: new Book(title:"The Stand"))
        def sw = new StringWriter()
        writable.writeTo( sw )
        ...
}

8.4.10 Static Compilation

JSON views are statically compiled. You can disable static compilation if you prefer by setting grails.views.json.compileStatic:

grails:
    views:
        json:
            compileStatic: false
If you disable static compilation rendering performance will suffer.

For model variables you need to declare the types otherwise you will get a compilation error:

model {
    Person person
}
json {
    name person.name
    age person.age
}

8.4.11 Testing

Although generally testing can be done using functional tests via an HTTP client, the JSON views plugin also provides a trait which helps in writing either unit or integration tests.

To use the trait import the grails.plugin.json.view.test.JsonViewTest class and apply it to any Spock or JUnit test:

import grails.plugin.json.view.test.*
import spock.lang.Specification
class MySpec extends Specification implements JsonViewTest {
    ...
}

The trait provides a number of different render method implementations that can either render a JSON view found in grails-app/views or render an inline String. For example to render an inline template:

void "Test render a raw GSON view"() {
    when:"A gson view is rendered"
    JsonRenderResult result = render '''
        model {
            String person
        }
        json.person {
            name person
        }
''', [person:"bob"] (1)

    then:"The json is correct"
    result.json.person.name == 'bob' (2)
}
1 Use the render method to return a JsonRenderResult passing in a String that is the inline template and a map that is the model
2 Assert the parsed JSON, represented by the json property, is correct

To render an existing view or template use named arguments to specify an absolute path to either a template or a view:

when:"A gson view is rendered"
def result = render(template: "/path/to/template", model:[age:10])

then:"The json is correct"
result.json.name == 'Fred'
result.json.age == 10

If you are writing a unit test, and the model involves a domain class, you may need to add the domain class to the mappingContext object in order for it to be rendered correctly:

when:"A gson view is rendered for a domain class"
mappingContext.addPersistentEntity(MyDomain)
def result = render(template: "/path/to/template", model:[myDomain:MyDomain])

then:"The json is correct"
result.json.name == 'Fred'
result.json.age == 10
Links generated by json views in a unit test may not match what they would normally generate in the standard environment. To fully test links, use a functional test.

New Testing Framework

Since the release of json views, a new testing framework was released for Grails. A new trait has been developed that works with the new testing framework that is designed to replace the existing trait. The existing trait will be left as is for backwards compatibility.

The new trait works exactly the same way as the old one, however since the new trait is designed to work with the new framework, there are several benefits you can take advantage of. The first is configuration. In the old trait the application configuration was not included in the template engine, which had the potential to produce incorrect results. Other benefits include extensibility and features like @OnceBefore.

To get started, add the org.grails:views-json-testing-support:7.0.0-SNAPSHOT dependency to your project and implement the JsonViewUnitTest trait in your test instead of JsonViewTest.

The new testing trait, like the testing framework, requires Spock.

8.4.12 Plugin Support

Grails plugins as well as standard Gradle Java/Groovy projects can provide json views to your application.

Grails Plugins

Since JSON views are compiled all of a plugin’s views and templates are available for use in your applications.

The view resolution will look through all of the application’s configured plugins for views that match a particular name. By default, the views a plugin supplies should be stored in grails-app/views, just like applications.

Basic Libraries

The most common use case to provide views in a standard library is to provide global templates. Global templates are templates designed to render a given class as JSON. In order to provide views in a standard Gradle project, you should configure your own view compilation task.

Below is an example Gradle build that adds a compileViews task for templates located into src/main/gson:

buildscript {
    repositories {
        maven { url "https://repo.grails.org/grails/core" }
    }
    dependencies {
        classpath "org.grails.plugins:views-gradle:7.0.0-SNAPSHOT"
    }
}

import grails.views.gradle.json.*

apply plugin:"java"

repositories {
    maven { url "https://repo.grails.org/grails/core" }
}

dependencies {
    compile "org.grails.plugins:views-json:7.0.0-SNAPSHOT"
    compileOnly "org.grails:grails-plugin-rest:3.1.7"
    compileOnly "jakarta.servlet:jakarta.servlet-api:6.0.0"
}

task( compileViews, type:JsonViewCompilerTask ) {
    source = project.file('src/main/gson')
    destinationDir = project.file('build/classes/main')
    packageName = ""
    classpath = configurations.compileClasspath + configurations.runtimeClasspath
}
classes.dependsOn compileViews

Once this is in place any applications that includes this library will have access to the templates provided.

For example if you want to render all instances of type foo.bar.Birthday create a template called src/main/gson/foo/bar/_birthday.gson then compile the template and place the JAR on the classpath of your application.

Customizing the Compile Task

Unless otherwise configured, the project name of the plugin (the gradle project.name) is used as the packageName when compiling JSON views.

In Gradle project.name is generally calculated from the current directory. That means that if there is mismatch between the current directory and your plugin name view resolution from a plugin could fail.

For example consider a plugin named FooBarGrailsPlugin, in this case Grails will search for views that match the plugin name foo-bar. However, if the directory where the plugin is located is called fooBar instead of foo-bar then view resolution will fail and the view will not be found when the plugin is installed into an application.

To resolve this issue you can customize the compileGsonViews task in the plugin’s build.gradle

compileGsonViews {
    packageName = "foo-bar"
}

By setting the packageName property to correctly match the convention of the plugin named (FooBarGrailsPlugin maps to foo-bar) view resolution will succeed.

8.4.13 Configuration

JSON views configuration can be altered within grails-app/conf/application.yml. Any of the properties within the JsonViewConfiguration interface can be set. The json view configuration extends GenericViewConfiguration, therefore any properties in that interface can be set as well.

For example:
grails:
    views:
        json:
            compileStatic: true
            cache: true
            ...

Alternatively you can register a new JsonViewConfiguration bean using the bean name jsonViewConfiguration in grails-app/conf/resources.groovy.

The same settings in grails-app/conf/application.yml will also be used by the Gradle plugin for production compilation.

The Gradle plugin compiles views using a forked compiler. You can configure the forked compilation task in Gradle as follows:

compileGsonViews {
    compileOptions.forkOptions.memoryMaximumSize = '512mb'
}

See the API for GroovyForkOptions for more information.

Changing the view base class

All JSON views subclass the JsonViewTemplate class by default.

You can however change the subclass (which should be a subclass of JsonViewTemplate) using configuration:

grails:
    views:
        json:
            compileStatic: true
            baseTemplateClass: com.example.MyCustomJsonViewTemplate

Adding New Helper Methods via Traits

Alternatively, rather than modifying the base class, you can instead just add new methods via traits.

For example the HttpView uses the Enhances annotation to add the page object to all views:

import grails.artefact.Enhances
import grails.views.Views

@Enhances(Views.TYPE)
trait HttpView {

    /**
     * @return The response object
     */
    Response response
    ...
}

The result is all JSON views have a response object that can be used to control the HTTP response:

response.header "Token", "foo"
The trait cannot be defined in the same project as you are compilation as it needs to be on the classpath of the project you are compiling. You will need to create a Grails plugin and use a multi-project build in this scenario.

Default Mime Types

The mime types that will be accepted by default for JSON view rendering is configurable.

grails:
    views:
        json:
            mimeTypes:
              - application/json
              - application/hal+json

Unicode Escaping

By default, unicode characters will not be escaped. If you would like unicode characters to be escaped in your output, set the following configuration.

grails:
    views:
        json:
            generator:
                escapeUnicode: true

Default Date Format

The default format for java.util.Date can be configured.

grails:
    views:
        json:
            generator:
                dateFormat: "yyyy-MM-dd'T'HH:mm:ss'Z'"

In addition, the default locale can also be specified.

grails:
    views:
        json:
            generator:
                locale: "en/US"

Default Time Zone

The default time zone can be configured. The value here will be passed to TimeZone.getTimeZone(…​)

grails:
    views:
        json:
            generator:
                timeZone: "GMT"

8.4.14 Custom Converters

It is possible to register custom converters to change how a given class is rendered with json views. To do so, create a class that implements Converter. Then you must register the class in src/main/resources/META-INF/services/grails.plugin.json.builder.JsonGenerator$Converter.

package foo

class MyConverter implements JsonGenerator.Converter {

    @Override
    boolean handles(Class<?> type) {
        CustomClass.isAssignableFrom(type)
    }

    @Override
    Object convert(Object value, String key) {
        ((CustomClass)value).name
    }
}


class CustomClass {
    String name
}

Because plugins could potentially provide converters, you can also determine the order by implementing the Ordered interface in your converter.

src/main/resources/META-INF/services/grails.plugin.json.builder.JsonGenerator$Converter
foo.MyCustomConverter
If you have multiple classes to register, put each one on it’s own line

8.4.15 IntelliJ Support

When opening .gson files in Intellij they should be opened with the regular Groovy editor.

The plugin includes an IntelliJ GDSL file that provides code completion when using IntelliJ IDEA.

Intellij GDSL is a way to describe the available methods and properties so that code completion is available to the developer when opening .gson files.

The GDSL file is generally kept up-to-date with the codebase, however if any variation is spotted please raise an issue.

8.4.16 Debugging Views

Generally views should be kept simple and if you arrive to the point where you need to debug a view you probably have too much logic in the view that would be better off handled by the controller prior to supplying the model.

Nevertheless here are a few view debugging tips to help identify problems in the view.

Introspecting the Model

Every JSON view is a Groovy script and like any Groovy script the model is defined in a binding variable. Therefore you can easily find out the model at any time by either logging or printing the binding variables:

model {
    Book book
}
// use the log variable
log.debug "Model is $binding.variables"
// use system out
System.out.println "Model is $binding.variables"
json g.render(book)
If you using the log variable then you will need to enabling logging for the grails.views package in grails-app/conf/logback.groovy

Connecting a Debugger

Some IDEs like Intellij IDE allow you to set break points and step debug within the view itself. As mentioned previously you shouldn’t arrive to this point and if you do you have too much logic in your view, but if you do need it the feature is there.

8.5 Markup Views

Markup Views are written in Groovy, end with the file extension gml and reside in the grails-app/views directory.

The Markup Views plugin uses Groovy’s MarkupTemplateEngine and you can mostly use the Groovy user guide as a reference for the syntax.

Example Markup View:

model {
    Iterable<Map> cars
}
xmlDeclaration()
cars {
    cars.each {
        car(make: it.make, model: it.model)
    }
}

This produces the following output given a model such as [cars:[[make:"Audi", model:"A5"]]]:

<?xml version='1.0'?>
<cars><car make='Audi' model='A5'/></cars>

For further examples see Groovy’s MarkupTemplateEngine documentation.

All Markup views subclass the MarkupViewTemplate class by default.

The MarkupViewTemplate superclass implements the MarkupView trait which in turn extends the the GrailsView trait.

8.5.1 Installation

To activate Markup views, add the following dependency to the dependencies block of your build.gradle:

compile "org.apache.grails:grails-views-markup"

To enable Gradle compilation of Markup views for production environment add the following to the buildscript dependencies block:

buildscript {
    ...
    dependencies {
        ...
        classpath platform('org.apache.grails:grails-gradle-bom:7.0.0-SNAPSHOT')
        classpath 'org.apache.grails:grails-gradle-plugins'
    }
}

Then apply the org.apache.grails.gradle.grails-markup Gradle plugin after any Grails core gradle plugins:

...
apply plugin: "org.apache.grails.gradle.grails-web"
apply plugin: "org.apache.grails.gradle.grails-markup"

This will add a compileMarkupViews task to Gradle that is executed when producing a JAR or WAR file.

8.5.2 Markup View API

All Markup views subclass the MarkupViewTemplate class by default.

The MarkupViewTemplate superclass implements the MarkupView trait which in turn extends the the GrailsView trait.

Much of the API is shared between JSON and Markup views. However, one difference compared to JSON views is that you must use this as a prefix when refering to properties from the parent class. For example to generate links this will produce a compilation error:

cars {
   cars.each {
       car(make: it.make, href: g.link(controller:'car'))
   }
}

However, the following works fine:

cars {
   cars.each {
       car(make: it.make, href: this.g.link(controller:'car'))
   }
}

Notice the this prefix when refering to this.g.link(..).

8.5.3 Configuration

Markup views configuration can be altered with grails-app/conf/application.yml. Any of the properties within the MarkupViewConfiguration class and Groovy’s TemplateConfiguration class can be set.

For example:

grails:
    views:
        markup:
            compileStatic: true
            cacheTemplates: true
            autoIndent: true
            ...

Alternatively you can register a new MarkupViewConfiguration bean using the bean name markupViewConfiguration in grails-app/conf/spring/resources.groovy.

8.6 URL Mappings

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/controllers/mypackage/UrlMappings.groovy.

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

package mypackage

class UrlMappings {
    static mappings = {
    }
}

8.6.1 Mapping to Controllers and Actions

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. 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 have mappings that all fall under a particular path you can group mappings with the group method:

group "/product", {
    "/apple"(controller:"product", id:"apple")
    "/htc"(controller:"product", id:"htc")
}

You can also create nested group url mappings:

group "/store", {
    group "/product", {
        "/$id"(controller:"product")
    }
}

To rewrite one URI onto another explicit URI (rather than a controller/action pair) do something like this:

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

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

8.6.2 Mapping to REST resources

Since Grails 2.3, it possible to create RESTful URL mappings that map onto controllers by convention. The syntax to do so is as follows:

"/books"(resources:'book')

You define a base URI and the name of the controller to map to using the resources parameter. The above mapping will result in the following URLs:

HTTP Method URI Grails Action

GET

/books

index

GET

/books/create

create

POST

/books

save

GET

/books/${id}

show

GET

/books/${id}/edit

edit

PUT

/books/${id}

update

DELETE

/books/${id}

delete

If you are not sure which mapping will be generated for your case just run the command url-mappings-report in your grails console. It will give you a really neat report for all the url mappings.

If you wish to include or exclude any of the generated URL mappings you can do so with the includes or excludes parameter, which accepts the name of the Grails action to include or exclude:

"/books"(resources:'book', excludes:['delete', 'update'])

or

"/books"(resources:'book', includes:['index', 'show'])

Explicit REST Mappings

As of Grails 3.1, if you prefer not to rely on a resources mapping to define your mappings then you can prefix any URL mapping with the HTTP method name (in lower case) to indicate the HTTP method it applies to. The following URL mapping:

"/books"(resources:'book')

Is equivalent to:

get "/books"(controller:"book", action:"index")
get "/books/create"(controller:"book", action:"create")
post "/books"(controller:"book", action:"save")
get "/books/$id"(controller:"book", action:"show")
get "/books/$id/edit"(controller:"book", action:"edit")
put "/books/$id"(controller:"book", action:"update")
delete "/books/$id"(controller:"book", action:"delete")

Notice how the HTTP method name is prefixed prior to each URL mapping definition.

Single resources

A single resource is a resource for which there is only one (possibly per user) in the system. You can create a single resource using the single parameter (as opposed to resources):

"/book"(single:'book')

This results in the following URL mappings:

HTTP Method URI Grails Action

GET

/book/create

create

POST

/book

save

GET

/book

show

GET

/book/edit

edit

PUT

/book

update

DELETE

/book

delete

The main difference is that the id is not included in the URL mapping.

Nested Resources

You can nest resource mappings to generate child resources. For example:

"/books"(resources:'book') {
  "/authors"(resources:"author")
}

The above will result in the following URL mappings:

HTTP Method URL Grails Action

GET

/books/${bookId}/authors

index

GET

/books/${bookId}/authors/create

create

POST

/books/${bookId}/authors

save

GET

/books/${bookId}/authors/${id}

show

GET

/books/${bookId}/authors/edit/${id}

edit

PUT

/books/${bookId}/authors/${id}

update

DELETE

/books/${bookId}/authors/${id}

delete

You can also nest regular URL mappings within a resource mapping:

"/books"(resources: "book") {
    "/publisher"(controller:"publisher")
}

This will result in the following URL being available:

HTTP Method URL Grails Action

GET

/books/${bookId}/publisher

index

To map a URI directly below a resource then use a collection block:

"/books"(resources: "book") {
    collection {
        "/publisher"(controller:"publisher")
    }
}

This will result in the following URL being available (without the ID):

HTTP Method URL Grails Action

GET

/books/publisher

index

Linking to RESTful Mappings

You can link to any URL mapping created with the g:link tag provided by Grails simply by referencing the controller and action to link to:

<g:link controller="book" action="index">My Link</g:link>

As a convenience you can also pass a domain instance to the resource attribute of the link tag:

<g:link resource="${book}">My Link</g:link>

This will automatically produce the correct link (in this case "/books/1" for an id of "1").

The case of nested resources is a little different as they typically required two identifiers (the id of the resource and the one it is nested within). For example given the nested resources:

"/books"(resources:'book') {
  "/authors"(resources:"author")
}

If you wished to link to the show action of the author controller, you would write:

// Results in /books/1/authors/2
<g:link controller="author" action="show" method="GET" params="[bookId:1]" id="2">The Author</g:link>

However, to make this more concise there is a resource attribute to the link tag which can be used instead:

// Results in /books/1/authors/2
<g:link resource="book/author" action="show" bookId="1" id="2">My Link</g:link>

The resource attribute accepts a path to the resource separated by a slash (in this case "book/author"). The attributes of the tag can be used to specify the necessary bookId parameter.

8.6.3 Redirects In URL Mappings

Since Grails 2.3, it is possible to define URL mappings which specify a redirect. When a URL mapping specifies a redirect, any time that mapping matches an incoming request, a redirect is initiated with information provided by the mapping.

When a URL mapping specifies a redirect the mapping must either supply a String representing a URI to redirect to or must provide a Map representing the target of the redirect. That Map is structured just like the Map that may be passed as an argument to the redirect method in a controller.

"/viewBooks"(redirect: [uri: '/books/list'])
"/viewAuthors"(redirect: [controller: 'author', action: 'list'])
"/viewPublishers"(redirect: [controller: 'publisher', action: 'list', permanent: true])

Request parameters that were part of the original request will not be included in the redirect by default. To include them it is necessary to add the parameter keepParamsWhenRedirect: true.

"/viewBooks"(redirect: [uri: '/books/list', keepParamsWhenRedirect: true])
"/viewAuthors"(redirect: [controller: 'author', action: 'list', keepParamsWhenRedirect: true])
"/viewPublishers"(redirect: [controller: 'publisher', action: 'list', permanent: true, keepParamsWhenRedirect: true])

8.6.4 Embedded Variables

Simple Variables

The previous section demonstrated how to map simple URLs with concrete "tokens". In URL mapping speak tokens are the sequence of characters between each slash, '/'. 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:

static mappings = {
   "/$blog/$year/$month/$day/$id"(controller: "blog", action: "show")
}

The above mapping would let you do things like:

/graemerocher/2007/01/10/my_funky_blog_entry

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:

static mappings = {
    "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")
}

With this mapping all of these URLs would match with only the relevant parameters being populated in the params object:

/graemerocher/2007/01/10/my_funky_blog_entry
/graemerocher/2007/01/10
/graemerocher/2007/01
/graemerocher/2007
/graemerocher

Optional File Extensions

If you wish to capture the extension of a particular path, then a special case mapping exists:

"/$controller/$action?/$id?(.$format)?"()

By adding the (.$format)? mapping you can access the file extension using the response.format property in a controller:

def index() {
    render "extension is ${response.format}"
}

Arbitrary Variables

You can also pass arbitrary parameters from the URL mapping into the controller by just setting them in the block passed to the mapping:

"/holiday/win" {
     id = "Marrakech"
     year = 2007
}

This variables will be available within the params object passed to the controller.

Dynamically Resolved Variables

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

"/holiday/win" {
     id = { params.id }
     isEligible = { session.user != null } // must be logged in
}

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.

8.6.5 Mapping to Views

You can resolve a URL to a view without a controller or action involved. For example 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
}

8.6.6 Mapping to Response Codes

Grails also lets you map HTTP response codes to controllers, actions, views or URIs. Just use a method name that matches the response code you are interested in:

static mappings = {
   "403"(controller: "errors", action: "forbidden")
   "404"(controller: "errors", action: "notFound")
   "500"(controller: "errors", action: "serverError")
}

Or you can specify custom error pages:

static mappings = {
   "403"(view: "/errors/forbidden")
   "404"(view: "/errors/notFound")
   "500"(view: "/errors/serverError")
}

You can also specify custom URIs:

static mappings = {
   "403"(uri: "/errors/forbidden")
   "404"(uri: "/errors/notFound")
   "500"(uri: "/errors/serverError")
}

Declarative Error Handling

In addition you can configure handlers for individual exceptions:

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")
}

With this configuration, an 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 handling view or controller action using the request’s exception attribute like so:

class ErrorsController {
    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 StackOverflowException.

8.6.7 Mapping to HTTP methods

URL mappings can also be configured to map based on the HTTP method (GET, POST, PUT or DELETE). This is very 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 ProductController:

static mappings = {
   "/product/$id"(controller:"product", action: "update", method: "PUT")
}

Note that if you specify a HTTP method other than GET in your URL mapping, you also have to specify it when creating the corresponding link by passing the method argument to g:link or g:createLink to get a link of the desired format.

8.6.8 Mapping Wildcards

Grails' URL mappings mechanism also supports wildcard mappings. For example consider the following mapping:

static mappings = {
    "/images/*.jpg"(controller: "image")
}

This mapping will match all paths to images such as /image/logo.jpg. Of course you can achieve the same effect with a variable:

static mappings = {
    "/images/$name.jpg"(controller: "image")
}

However, you can also use double wildcards to match more than one level below:

static mappings = {
    "/images/**.jpg"(controller: "image")
}

In this cases the mapping will match /image/logo.jpg as well as /image/other/logo.jpg. Even better you can use a double wildcard variable:

static mappings = {
    // will match /image/logo.jpg and /image/other/logo.jpg
    "/images/$name**.jpg"(controller: "image")
}

In this case it will store the path matched by the wildcard inside a name parameter obtainable from the params object:

def name = params.name
println name // prints "logo" or "other/logo"

If you use wildcard URL mappings then you may want to exclude certain URIs from Grails' URL mapping process. To do this you can provide an excludes setting inside the UrlMappings.groovy class:

class UrlMappings {
    static excludes = ["/images/*", "/css/*"]
    static mappings = {
        ...
    }
}

In this case Grails won’t attempt to match any URIs that start with /images or /css.

8.6.9 Automatic Link Re-Writing

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

static mappings = {
   "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")
}

If you use the link tag as follows:

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

Grails will automatically re-write the URL in the correct format:

<a href="/fred/2007">My Blog</a>
<a href="/fred/2007/10">My Blog - October 2007 Posts</a>

8.6.10 Applying Constraints

URL Mappings also support Grails' unified validation constraints mechanism, which lets you further "constrain" how a URL is matched. For example, if we revisit the blog sample code from earlier, the mapping currently looks like this:

static mappings = {
   "/$blog/$year?/$month?/$day?/$id?"(controller:"blog", action:"show")
}

This allows URLs such as:

/graemerocher/2007/01/10/my_funky_blog_entry

However, it would also allow:

/graemerocher/not_a_year/not_a_month/not_a_day/my_funky_blog_entry

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:

"/$blog/$year?/$month?/$day?/$id?" {
     controller = "blog"
     action = "show"
     constraints {
          year(matches:/\\\d{4}/)
          month(matches:/\\\d{2}/)
          day(matches:/\\\d{2}/)
     }
}

In this case the constraints ensure that the year, month and day parameters match a particular valid pattern thus relieving you of that burden later on.

8.6.11 Named URL Mappings

URL Mappings also support named mappings, that is mappings which have a name associated with them. The name may be used to refer to a specific mapping when links are generated.

The syntax for defining a named mapping is as follows:

static mappings = {
   name <mapping name>: <url pattern> {
      // ...
   }
}

For example:

static mappings = {
    name personList: "/showPeople" {
        controller = 'person'
        action = 'list'
    }
    name accountDetails: "/details/$acctNumber" {
        controller = 'product'
        action = 'accountDetails'
    }
}

The mapping may be referenced in a link tag in a GSP.

<g:link mapping="personList">List People</g:link>

That would result in:

<a href="/showPeople">List People</a>

Parameters may be specified using the params attribute.

<g:link mapping="accountDetails" params="[acctNumber:'8675309']">
    Show Account
</g:link>

That would result in:

<a href="/details/8675309">Show Account</a>

Alternatively you may reference a named mapping using the link namespace.

<link:personList>List People</link:personList>

That would result in:

<a href="/showPeople">List People</a>

The link namespace approach allows parameters to be specified as attributes.

<link:accountDetails acctNumber="8675309">Show Account</link:accountDetails>

That would result in:

<a href="/details/8675309">Show Account</a>

To specify attributes that should be applied to the generated href, specify 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.

<link:accountDetails attrs="[class: 'fancy']" acctNumber="8675309">
    Show Account
</link:accountDetails>

That would result in:

<a href="/details/8675309" class="fancy">Show Account</a>

8.6.12 Customizing URL Formats

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

grails-app/conf/application.groovy
grails.web.url.converter = 'hyphenated'

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

src/main/groovy/com/myapplication/MyUrlConverterImpl.groovy
package com.myapplication

class MyUrlConverterImpl implements grails.web.UrlConverter {

    String toUrlElement(String propertyOrClassName) {
        // return some representation of a property or class name that should be used in URLs...
    }
}
grails-app/conf/spring/resources.groovy
beans = {
    "${grails.web.UrlConverter.BEAN_NAME}"(com.myapplication.MyUrlConverterImpl)
}

8.6.13 Namespaced Controllers

If an application defines multiple controllers with the same name in different packages, the controllers must be defined in a namespace. The way to define a namespace for a controller is to define a static property named namespace in the controller and assign a String to the property that represents the namespace.

grails-app/controllers/com/app/reporting/AdminController.groovy
package com.app.reporting

class AdminController {

    static namespace = 'reports'

    // ...
}
grails-app/controllers/com/app/security/AdminController.groovy
package com.app.security

class AdminController {

    static namespace = 'users'

    // ...
}

When defining url mappings which should be associated with a namespaced controller, the namespace variable needs to be part of the URL mapping.

grails-app/controllers/UrlMappings.groovy
class UrlMappings {

    static mappings = {
        '/userAdmin' {
            controller = 'admin'
            namespace = 'users'
        }

        '/reportAdmin' {
            controller = 'admin'
            namespace = 'reports'
        }

        "/$namespace/$controller/$action?"()
    }
}

Reverse URL mappings also require that the namespace be specified.

<g:link controller="admin" namespace="reports">Click For Report Admin</g:link>
<g:link controller="admin" namespace="users">Click For User Admin</g:link>

When resolving a URL mapping (forward or reverse) to a namespaced controller, a mapping will only match if the namespace has been provided. If the application provides several controllers with the same name in different packages, at most 1 of them may be defined without a namespace property. If there are multiple controllers with the same name that do not define a namespace property, the framework will not know how to distinguish between them for forward or reverse mapping resolutions.

It is allowed for an application to use a plugin which provides a controller with the same name as a controller provided by the application and for neither of the controllers to define a namespace property as long as the controllers are in separate packages. For example, an application may include a controller named com.accounting.ReportingController and the application may use a plugin which provides a controller named com.humanresources.ReportingController. The only issue with that is the URL mapping for the controller provided by the plugin needs to be explicit in specifying that the mapping applies to the ReportingController which is provided by the plugin.

See the following example.

static mappings = {
    "/accountingReports" {
        controller = "reporting"
    }
    "/humanResourceReports" {
        controller = "reporting"
        plugin = "humanResources"
    }
}

With that mapping in place, a request to /accountingReports will be handled by the ReportingController which is defined in the application. A request to /humanResourceReports will be handled by the ReportingController which is provided by the humanResources plugin.

There could be any number of ReportingController controllers provided by any number of plugins but no plugin may provide more than one ReportingController even if they are defined in separate packages.

Assigning a value to the plugin variable in the mapping is only required if there are multiple controllers with the same name available at runtime provided by the application and/or plugins. If the humanResources plugin provides a ReportingController and there is no other ReportingController available at runtime, the following mapping would work.

static mappings = {
    "/humanResourceReports" {
        controller = "reporting"
    }
}

It is best practice to be explicit about the fact that the controller is being provided by a plugin.

8.7 CORS

Spring Boot provides CORS support out of the box, but it is difficult to configure in a Grails application due to the way UrlMappings are used instead of annotations that define URLs. Starting with Grails 3.2.1, we have added a way to configure CORS that makes sense in a Grails application.

Once enabled, the default setting is "wide open".

application.yml
grails:
    cors:
        enabled: true

That will produce a mapping to all urls /** with:

allowedOrigins

['*']

allowedMethods

['*']

allowedHeaders

['*']

exposedHeaders

null

maxAge

1800

allowCredentials

false

Some of these settings come directly from Spring Boot and can change in future versions. See Spring CORS Configuration Documentation

All of those settings can be easily overridden.

application.yml
grails:
    cors:
        enabled: true
        allowedOrigins:
            - http://localhost:5000

In the example above, the allowedOrigins setting will replace [*].

You can also configure different URLs.

application.yml
grails:
    cors:
        enabled: true
        allowedHeaders:
            - Content-Type
        mappings:
            '[/api/**]':
                allowedOrigins:
                    - http://localhost:5000
                # Other configurations not specified default to the global config

Note that the mapping key must be made with bracket notation (see https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-Configuration-Binding#map-based-binding), which is a breaking change between Spring Boot 1.5 (Grails 3) and Spring Boot 2 (Grails 4).

Specifying at least one mapping will disable the creation of the global mapping (/**). If you wish to keep that setting, you should specify it along with your other mappings.

The settings above will produce a single mapping of /api/** with the following settings:

allowedOrigins

['http://localhost:5000']

allowedMethods

['*']

allowedHeaders

['Content-Type']

exposedHeaders

null

maxAge

1800

allowCredentials

false

If you don’t wish to override any of the default settings, but only want to specify URLs, you can do so like this example:

application.yml
grails:
    cors:
        enabled: true
        mappings:
            '[/api/**]': inherit

8.8 Interceptors

Grails provides standalone Interceptors using the create-interceptor command:

$ grails create-interceptor MyInterceptor

The above command will create an Interceptor in the grails-app/controllers directory with the following default contents:

class MyInterceptor {

  boolean before() { true }

  boolean after() { true }

  void afterView() {
    // no-op
  }

}

Interceptors vs Filters

In versions of Grails prior to Grails 3.0, Grails supported the notion of filters. These are still supported for backwards compatibility but are considered deprecated.

The new interceptors concept in Grails 3.0 is superior in a number of ways, most significantly interceptors can use Groovy’s CompileStatic annotation to optimize performance (something which is often critical as interceptors can be executed for every request.)

8.8.1 Defining Interceptors

By default interceptors will match the controllers with the same name. For example if you have an interceptor called BookInterceptor then all requests to the actions of the BookController will trigger the interceptor.

An Interceptor implements the Interceptor trait and provides 3 methods that can be used to intercept requests:

/**
 * Executed before a matched action
 *
 * @return Whether the action should continue and execute
 */
boolean before() { true }

/**
 * Executed after the action executes but prior to view rendering
 *
 * @return True if view rendering should continue, false otherwise
 */
boolean after() { true }

/**
 * Executed after view rendering completes
 */
void afterView() {}

As described above the before method is executed prior to an action and can cancel the execution of the action by returning false.

The after method is executed after an action executes and can halt view rendering if it returns false. The after method can also modify the view or model using the view and model properties respectively:

boolean after() {
  model.foo = "bar" // add a new model attribute called 'foo'
  view = 'alternate' // render a different view called 'alternate'
  true
}

The afterView method is executed after view rendering completes. If an exception occurs, the exception is available using the throwable property of the Interceptor trait.

8.8.2 Matching Requests with Interceptors

As mention in the previous section, by default an interceptor will match only requests to the associated controller by convention. However you can configure the interceptor to match any request using the match or matchAll methods defined in the Interceptor API.

The matching methods return a Matcher instance which can be used to configure how the interceptor matches the request.

For example the following interceptor will match all requests except those to the login controller:

class AuthInterceptor {
  AuthInterceptor() {
    matchAll()
    .excludes(controller:"login")
  }

  boolean before() {
    // perform authentication
  }
}

You can also perform matching using named argument:

class LoggingInterceptor {
  LoggingInterceptor() {
    match(controller:"book", action:"show") // using strings
    match(controller: ~/(author|publisher)/) // using regex
  }

  boolean before() {
    ...
  }
}

You can use any number of matchers defined in your interceptor. They will be executed in the order in which they have been defined. For example the above interceptor will match for all of the following:

  • when the show action of BookController is called

  • when AuthorController or PublisherController is called

All named arguments except for uri accept either a String or a Regex expression. The uri argument supports a String path that is compatible with Spring’s AntPathMatcher. The possible named arguments are:

  • namespace - The namespace of the controller

  • controller - The name of the controller

  • action - The name of the action

  • method - The HTTP method

  • uri - The URI of the request. If this argument is used then all other arguments will be ignored and only this will be used.

8.8.3 Ordering Interceptor Execution

Interceptors can be ordered by defining an order property that defines a priority.

For example:

class AuthInterceptor {

  int order = HIGHEST_PRECEDENCE

  ...
}

The default value of the order property is 0. Interceptor execution order is determined by sorting the order property in an ascending direction and executing the lowest numerically ordered interceptor first.

The values HIGHEST_PRECEDENCE and LOWEST_PRECEDENCE can be used to define filters that should should run first or last respectively.

Note that if you write an interceptor that is to be used by others it is better increment or decrement the HIGHEST_PRECEDENCE and LOWEST_PRECEDENCE to allow other interceptors to be inserted before or after the interceptor you are authoring:

int order = HIGHEST_PRECEDENCE + 50

// or

int order = LOWEST_PRECEDENCE - 50

To find out the computed order of interceptors you can add a debug logger to logback-spring.xml as follows:

<logger name="grails.artefact.Interceptor" level="DEBUG" />

You can override any interceptors default order by using bean override configuration in grails-app/conf/application.yml:

beans:
  authInterceptor:
    order: 50

Or in grails-app/conf/application.groovy:

beans {
  authInterceptor {
    order = 50
  }
}

Thus giving you complete control over interceptor execution order.

8.9 Content Negotiation

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/application.yml using the grails.mime.types setting:

grails:
    mime:
        types:
            all: '*/*'
            atom: application/atom+xml
            css: text/css
            csv: text/csv
            form: application/x-www-form-urlencoded
            html:
              - text/html
              - application/xhtml+xml
            js: text/javascript
            json:
              - application/json
              - text/json
            multipartForm: multipart/form-data
            rss: application/rss+xml
            text: text/plain
            hal:
              - application/hal+json
              - application/hal+xml
            xml:
              - text/xml
              - application/xml

The setting can also be done in grails-app/conf/application.groovy as shown below:

grails.mime.types = [ // the first one is the default format
    all:           '*/*', // 'all' maps to '*' or the first available format in withFormat
    atom:          'application/atom+xml',
    css:           'text/css',
    csv:           'text/csv',
    form:          'application/x-www-form-urlencoded',
    html:          ['text/html','application/xhtml+xml'],
    js:            'text/javascript',
    json:          ['application/json', 'text/json'],
    multipartForm: 'multipart/form-data',
    rss:           'application/rss+xml',
    text:          'text/plain',
    hal:           ['application/hal+json','application/hal+xml'],
    xml:           ['text/xml', 'application/xml']
]

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. The first one is the default format.

Content Negotiation using the format Request Parameter

Let’s say a controller action can return a resource in a variety of formats: HTML, XML, and JSON. What format will the client get? The easiest and most reliable way for the client to control this is through a format URL parameter.

So if you, as a browser or some other client, want a resource as XML, you can use a URL like this:

http://my.domain.org/books.xml
The request parameters format is allowed as well http://my.domain.org/books?format=xml, but the default Grails URL Mapping get "/$controller(.$format)?"(action:"index") will override the format parameter with null. So the default mapping should be updated to get "/$controller"(action:"index").

The result of this on the server side is a format property on the response object with the value xml .

You can also define this parameter in the URL Mappings definition:

"/book/list"(controller:"book", action:"list") {
    format = "xml"
}

You could code your controller action to return XML based on this property, but you can also make use of the controller-specific withFormat() method:

This example requires the addition of the org.apache.grails:grails-converters plugin
import grails.converters.JSON
import grails.converters.XML

class BookController {

    def list() {
        def books = Book.list()

        withFormat {
            html bookList: books
            json { render books as JSON }
            xml { render books as XML }
            '*' { render books as JSON }
        }
    }
}

In this example, Grails will only execute the block inside withFormat() that matches the requested content type. So if the preferred format is html then Grails will execute the html() call only. Each 'block' can either be a map model for the corresponding view (as we are doing for 'html' in the above example) or a closure. The closure can contain any standard action code, for example it can return a model or render content directly.

When no format matches explicitly, a * (wildcard) block can be used to handle all other formats.

There is a special format, "all", that is handled differently from the explicit formats. If "all" is specified (normally this happens through the Accept header - see below), then the first block of withFormat() is executed when there isn’t a * (wildcard) block available.

You should not add an explicit "all" block. In this example, a format of "all" will trigger the html handler (html is the first block and there is no * block).

withFormat {
    html bookList: books
    json { render books as JSON }
    xml { render books as XML }
}
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.

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, newer browsers send more interesting values such as this one sent by Firefox:

text/xml, application/xml, application/xhtml+xml, text/html;q=0.9, \
    text/plain;q=0.8, image/png, */*;q=0.5

This particular accept header is unhelpful because it indicates that XML is the preferred response format whereas the user is really expecting HTML. That’s why Grails ignores the accept header by default for browsers. However, non-browser clients are typically more specific in their requirements and can send accept headers such as

application/json

As mentioned the default configuration in Grails is to ignore the accept header for browsers. This is done by the configuration setting grails.mime.disable.accept.header.userAgents, which is configured to detect the major rendering engines and ignore their ACCEPT headers. This allows Grails' content negotiation to continue to work for non-browser clients:

grails.mime.disable.accept.header.userAgents = ['Gecko', 'WebKit', 'Presto', 'Trident']

For example, if it sees the accept header above ('application/json') it will set format to json as you’d expect. And of course this works with the withFormat() method in just the same way as when the format URL parameter is set (although the URL parameter takes precedence).

An accept header of '*/\*' results in a value of all for the format property.

If the accept header is used but contains no registered content types, Grails will assume a broken browser is making the request and will set the HTML format - note that this is different from how the other content negotiation modes work as those would activate the "all" format!

Request format vs. Response format

As of Grails 2.0, there is a separate notion of the request format and the response format. The request format is dictated by the CONTENT_TYPE header and is typically used to detect if the incoming request can be parsed into XML or JSON, whilst the response format uses the file extension, format parameter or ACCEPT header to attempt to deliver an appropriate response to the client.

The withFormat available on controllers deals specifically with the response format. If you wish to add logic that deals with the request format then you can do so using a separate withFormat method available on the request:

request.withFormat {
    xml {
        // read XML
    }
    json {
        // read JSON
    }
}

Content Negotiation with URI Extensions

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

/book/list.xml

This works as a result of the default URL Mapping definition which is:

"/$controller/$action?/$id?(.$format)?"{

Note the inclusion of the format variable in the path. If you do not wish to use content negotiation via the file extension then simply remove this part of the URL mapping:

"/$controller/$action?/$id?"{

Testing Content Negotiation

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

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
}

Or you can set the format parameter to achieve a similar effect:

void testJavascriptOutput() {
    def controller = new TestController()
    controller.params.format = 'js'

    controller.testAction()
    assertEquals "alert('hello')", controller.response.contentAsString
}
OSZAR »