grails create-controller book
8.1 Controllers
Version: 4.0.11
Table of Contents
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:
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.
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")
-
A domain class instance:
// 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:
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 .
|
// 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.
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.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.
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:
package databinding
class Gadget {
Shape expandedShape
Shape compressedShape
}
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:
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:
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
.
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.
package bindingdemo
class Widget {
String name
Integer size
}
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.
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:
package example
class BookController {
def index() {
respond Book.list()
}
}
The respond
method will take the followings steps:
-
If the client
Accept
header specifies a media type (for exampleapplication/json
) use that -
If the file extension of the URI (for example
/books.json
) includes a format defined in thegrails.mime.types
property ofgrails-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:
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 |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Using this convention you can reference the argument passed to respond
from within your view:
@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:
// 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:
controllers:
upload:
maxFileSize: 2000000
maxRequestSize: 2000000
maxFileSize
= The maximum size allowed for uploaded files.
maxRequestSize
= The maximum size allowed for multipart/form-data requests.
You should keep in mind OWASP recommendations - Unrestricted File Upload
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.
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:
|
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.
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.
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…
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…
package com.demo
trait DatabaseExceptionHandler {
def handleSQLException(SQLException e) {
// handle SQLException
}
def handleBatchUpdateException(BatchUpdateException e) {
// handle BatchUpdateException
}
}
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.