6.1 Controllers - Reference Documentation
Authors: Graeme Rocher, Peter Ledbrook, Marc Palmer, Jeff Brown, Luke Daley, Burt Beckwith
Version: null
Table of Contents
6.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 withController 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.
6.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
grails-app/controllers/myapp/BookController.groovy:package myappclass BookController { def index() { }
}BookController by default maps to the /book URI (relative to your application root).Thecreate-controllerandgenerate-controllercommands 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
}
}/book/list URI by default thanks to the property being named list.Public Methods as Actions
In earlier versions of Grails actions were implemented with Closures. This is still supported, but the preferred approach is to use methods.Leveraging methods instead of Closure properties has some advantages:- Memory efficient
- Allow use of stateless controllers (
singletonscope) - You can override actions from subclasses and call the overridden superclass method with
super.actionName() - Methods can be intercepted with standard proxying mechanisms, something that is complicated to do with Closures since they're fields.
grails.compile.artefacts.closures.convert property to true in BuildConfig.groovy:
grails.compile.artefacts.closures.convert = true
If a controller class extends some other class which is not defined under the grails-app/controllers/ directory, methods inherited from that class are not converted to controller actions. If the intent is to expose those inherited methods as controller actions the methods may be overridden in the subclass and the subclass method may invoke the method in the super class.
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
defaultActionproperty:
static defaultAction = "list"
6.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"]
}
}class BookController {
def find() {
def findBy = params.findBy
def appContext = request.foo
def loggedUser = session.logged_user
}
}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
}list 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
By default, a new controller instance is created for each request. In fact, because the controller isprototype scoped, it is thread-safe since each request happens on its own thread.You can change this behaviour by placing a controller in a particular scope. The supported 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 sessionsingleton- Only one instance of the controller ever exists (recommended for actions as methods)
scope property to your class with one of the valid scope values listed above, for examplestatic scope = "singleton"
Config.groovy 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. Setting a default scope other thanprototypemay also lead to unexpected behaviors if you have controllers provided by installed plugins that expect that the scope isprototype.
6.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.If no explicit model is returned the controller's properties will be used as the model, thus allowing you to write code like this:
class BookController { List books
List authors def list() {
books = Book.list()
authors = Author.list()
}
}This is possible due to the fact that controllers are prototype scoped. In other words a new controller is created for each request. Otherwise code such as the above would not be thread-safe, and all users would share the same data.In the above example the
books and authors properties will be available in the view.A more advanced approach is to return an instance of the Spring ModelAndView class:import org.springframework.web.servlet.ModelAndViewdef 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 ]) }
attributesapplication
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 locationgrails-app/views/book/show.gsp for this list action:class BookController {
def show() {
[book: Book.get(params.id)]
}
}def show() {
def map = [book: Book.get(params.id)]
render(view: "display", model: map)
}grails-app/views/book/display.gsp. Notice that Grails automatically qualifies the view location with the book directory of the grails-app/views directory. This is convenient, but to access shared views you need instead you can use an absolute path instead of a relative one:def show() {
def map = [book: Book.get(params.id)]
render(view: "/shared/display", model: map)
}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.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 flexiblerender method can be used:render "Hello World!"// 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")
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 }
MarkupBuilder). To correctly output a <form> element, use the following:def login() {
// …
body {
h1 'Hello'
builder.form {
}
}
// …
}6.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
}
…
}
}sendRedirect method.The redirect method expects one of:
- Another closure within the same controller class:
// Call the login action within the same class redirect(action: login)
- 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")params argument of the method:redirect(action: 'myaction', params: [myparam: "myvalue"])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)redirect(controller: "test", action: "show", fragment: "profile")
Chaining
Actions can also be chained. Chaining allows the model to be retained from one action to the next. For example calling thefirst 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])
}
}[one: 1, two: 2, three: 3]
chainModel map. This dynamic property only exists in actions following the call to the chain method:class ChainController { def nextInChain() {
def model = chainModel.myModel
…
}
}redirect method you can also pass parameters to the chain method:chain(action: "action1", model: [one: 1], params: [myparam: "param1"])
6.1.5 Controller Interceptors
Often it is useful to intercept processing based on either request, session or application state. This can be achieved with action interceptors. There are currently two types of interceptors: before and after.If your interceptor is likely to apply to more than one controller, you are almost certainly better off writing a Filter. Filters can be applied to multiple controllers or URIs without the need to change the logic of each controller
Before Interception
ThebeforeInterceptor intercepts processing before the action is executed. If it returns false then the intercepted action will not be executed. The interceptor can be defined for all actions in a controller as follows:def beforeInterceptor = {
println "Tracing action ${actionUri}"
}def beforeInterceptor = [action: this.&auth, except: 'login']// defined with private scope, so it's not considered an action private auth() { if (!session.user) { redirect(action: 'login') return false } }def login() { // display login page }
auth. A private method is used so that it is not exposed as an action to the outside world. The beforeInterceptor then defines an interceptor that is used on all actions except the login action and it executes the auth method. The auth method is referenced using Groovy's method pointer syntax. Within the method it detects whether there is a user in the session, and if not it redirects to the login action and returns false, causing the intercepted action to not be processed.After Interception
Use theafterInterceptor property to define an interceptor that is executed after an action:def afterInterceptor = { model ->
println "Tracing action ${actionUri}"
}def afterInterceptor = { model, modelAndView ->
println "Current view is ${modelAndView.viewName}"
if (model.someVar) modelAndView.viewName = "/mycontroller/someotherview"
println "View is now ${modelAndView.viewName}"
}modelAndView may be null if the action being intercepted called redirect or render.Interception Conditions
Rails users will be familiar with the authentication example and how the 'except' condition was used when executing the interceptor (interceptors are called 'filters' in Rails; this terminology conflicts with Servlet filter terminology in Java):def beforeInterceptor = [action: this.&auth, except: 'login']def beforeInterceptor = [action: this.&auth, except: ['login', 'register']]def beforeInterceptor = [action: this.&auth, only: ['secure']]6.1.6 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.Grails uses Spring's underlying data binding capability to perform data binding.Binding Request Data to the Model
There are two ways to bind request parameters onto the properties of a domain class. The first involves using a domain classes' Map constructor:def save() {
def b = new Book(params)
b.save()
}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
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()
}Data binding and Single-ended Associations
If you have aone-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
.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)null by passing the literal String "null". For example:/book/save?author.id=nullData 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 aSet 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}" />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" />
Set based association it is critical that you render the mark-up in the same order that you plan to do the update in. This is because a Set has no concept of order, so although we're referring to books0 and books1 it is not guaranteed that the order of the association will be correct on the server side unless you apply some explicit sorting yourself.This is not a problem if you use List based associations, since a List has a defined order and an index you can refer to. This is also true of Map based associations.Note also that if the association you are binding to has a size of 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" />
<g:textField name="books[0].title" value="the Stand" /> <g:textField name="books[1].title" value="the Shining" /> <g:textField name="books[5].title" value="Red Madder" />
List using the same .id syntax as you would use with a single-ended association. For example:<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}" />
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': '']"/>books0 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': '']"/>Map property images under a key of "cover".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
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)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) {
// …
}
}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
controller.errors.hasErrors() will be true, controller.errors.errorCount will be equal to 1 and controller.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.RequestParameterclass 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
}Book that uses the java.net.URL class to represent URLs. Given an incoming request such as:/book/save?publisherURL=a-bad-url
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!" }
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 URLtypeMismatch.Book.publisherURL=The publisher URL you specified is not a valid URL
Data Binding and Security concerns
When batch updating properties from request parameters you need to be careful not to allow clients to bind malicious data to domain classes 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
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)bindData method also lets you exclude certain parameters that you don't want updated:def p = new Person()
bindData(p, params, [exclude: 'dateOfBirth'])def p = new Person()
bindData(p, params, [include: ['firstName', 'lastName]])
Note that 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.
6.1.7 XML and JSON Responses
Using the render method to output XML
Grails supports a few different ways to produce XML and JSON responses. The first is the render method.Therender method can be passed a block of code to do mark-up building in XML:def list() { def results = Book.list() render(contentType: "text/xml") {
books {
for (b in results) {
book(title: b.title)
}
}
}
}<books> <book title="The Stand" /> <book title="The Shining" /> </books>
def list() { def books = Book.list() // naming conflict here render(contentType: "text/xml") {
books {
for (b in results) {
book(title: b.title)
}
}
}
}books which Groovy attempts to invoke as a method.Using the render method to output JSON
Therender method can also be used to output JSON:def list() { def results = Book.list() render(contentType: "text/json") {
books = array {
for (b in results) {
book title: b.title
}
}
}
}[
{title:"The Stand"},
{title:"The Shining"}
]Automatic XML Marshalling
Grails also supports automatic marshalling of domain classes to XML using special converters.To start off with, import thegrails.converters package into your controller:import grails.converters.*render Book.list() as XML
<?xml version="1.0" encoding="ISO-8859-1"?> <list> <book id="1"> <author>Stephen King</author> <title>The Stand</title> </book> <book id="2"> <author>Stephen King</author> <title>The Shining</title> </book> </list>
def xml = Book.list().encodeAsXML() render xml
Automatic JSON Marshalling
Grails also supports automatic marshalling to JSON using the same mechanism. Simply substituteXML with JSON:render Book.list() as JSON
[
{"id":1,
"class":"Book",
"author":"Stephen King",
"title":"The Stand"},
{"id":2,
"class":"Book",
"author":"Stephen King",
"releaseDate":new Date(1194127343161),
"title":"The Shining"}
]encodeAsJSON to achieve the same effect.
6.1.8 More on JSONBuilder
The previous section on on XML and JSON responses covered simplistic examples of rendering XML and JSON responses. Whilst the XML builder used by Grails is the standard XmlSlurper found in Groovy, the JSON builder is a custom implementation specific to Grails.JSONBuilder and Grails versions
JSONBuilder behaves different depending on the version of Grails you use. For version below 1.2 the deprecated grails.web.JSONBuilder class is used. This section covers the usage of the Grails 1.2 JSONBuilderFor backwards compatibility the oldJSONBuilder class is used with the render method for older applications; to use the newer/better JSONBuilder class set the following in Config.groovy:grails.json.legacy.builder = falseRendering Simple Objects
To render a simple JSON object just set properties within the context of the Closure:render(contentType: "text/json") { hello = "world" }
{"hello":"world"}Rendering JSON Arrays
To render a list of objects simple assign a list:render(contentType: "text/json") {
categories = ['a', 'b', 'c']
}{"categories":["a","b","c"]}render(contentType: "text/json") { categories = [ { a = "A" }, { b = "B" } ] }
{"categories":[ {"a":"A"} , {"b":"B"}] }element method to return a list as the root:render(contentType: "text/json") {
element 1
element 2
element 3
}[1,2,3]
Rendering Complex Objects
Rendering complex objects can be done with Closures. For example:render(contentType: "text/json") { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }
{"categories":["a","b","c"],"title":"Hello JSON","information":{"pages":10}}Arrays of Complex Objects
As mentioned previously you can nest complex objects within arrays using Closures:render(contentType: "text/json") { categories = [ { a = "A" }, { b = "B" } ] }
array method to build them up dynamically:def results = Book.list() render(contentType: "text/json") { books = array { for (b in results) { book title: b.title } } }
Direct JSONBuilder API Access
If you don't have access to therender method, but still want to produce JSON you can use the API directly:def builder = new JSONBuilder()def result = builder.build { categories = ['a', 'b', 'c'] title = "Hello JSON" information = { pages = 10 } }// prints the JSON text println result.toString()def sw = new StringWriter() result.render sw
6.1.9 Uploading Files
Programmatic File 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>
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')
}InputStream and so on with the MultipartFile interface.File Uploads through Data Binding
File uploads can also be performed using data binding. Consider thisImage domain class:class Image {
byte[] myFile static constraints = {
// Limit upload file size to 2MB
myFile maxSize: 1024 * 1024 * 2
}
}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)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
}6.1.10 Command Objects
Grails controllers support the concept of command objects. A command object is similar to a form bean in a framework like Struts, and they are useful for populating a subset of the properties needed to update a domain class. Or where there is no domain class required for the interaction, but you need features such as data binding and validation.Declaring Command Objects
Command objects are typically declared in the same source file as a controller, directly below the controller class definition. For example:class UserController {
…
}class LoginCommand {
String username
String password static constraints = {
username(blank: false, minSize: 6)
password(blank: false, minSize: 6)
}
}Using Command Objects
To use command objects, controller actions may optionally specify any number of command object parameters. The parameter types must be supplied so that Grails knows what objects to create, populate and validate.Before the controller action is executed Grails will automatically create an instance of the command object class, populate its properties with by binding the request parameters, and validate the command object. For example:class LoginController { def login = { LoginCommand cmd ->
if (cmd.hasErrors()) {
redirect(action: 'loginForm')
return
} // work with the command object data
}
}class LoginController {
def login(LoginCommand cmd) {
if (cmd.hasErrors()) {
redirect(action: 'loginForm')
return
} // work with the command object data
}
}Command Objects and Dependency Injection
Command objects can participate in dependency injection. This is useful if your command object has some custom validation logic uses Grails services:class LoginCommand { def loginService String username
String password static constraints = {
username validator: { val, obj ->
obj.loginService.canLogin(obj.username, obj.password)
}
}
}loginService bean which is injected by name from the Spring ApplicationContext.
6.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" ...>withForm {
// good request
}.invalidToken {
// bad request
}invalidToken method then by default Grails will store the invalid token in a flash.invalidToken variable and redirect the request back to the original page. This can then be checked in the view:<g:if test="${flash.invalidToken}"> Don't click the button twice! </g:if>
The withForm tag makes use of the session and hence requires session affinity or clustered sessions if used in a cluster.
6.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')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)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
}6.1.13 Asynchronous Request Processing
Grails support asynchronous request processing as provided by the Servlet 3.0 specification. To enable the async features you need to set your servlet target version to 3.0 in BuildConfig.groovy:grails.servlet.version = "3.0"With a Servlet target version of 3.0 you can only deploy on Servlet 3.0 containers such as Tomcat 7 and above.
Asynchronous Rendering
You can render content (templates, binary data etc.) in an asynchronous manner by calling thestartAsync method which returns an instance of the Servlet 3.0 AsyncContext. Once you have a reference to the AsyncContext you can use Grails' regular render method to render content:def index() {
def ctx = startAsync()
ctx.start {
new Book(title:"The Stand").save()
render template:"books", model:[books:Book.list()]
ctx.complete()
}
}complete() method to terminate the connection.Resuming an Async Request
You resume processing of an async request (for example to delegate to view rendering) by using thedispatch method of the AsyncContext class:def index() {
def ctx = startAsync()
ctx.start {
// do working
…
// render view
ctx.dispatch()
}
}
