Controller Dynamic Methods & Properties
Properties
actionUri
Description
The relative Uri of the action
controllerUri
Description
The relative Uri of the controller
actionName
Description
The name of the current action
controllerName
Description
The name of the current controller
flash
Description
A map that allows temporary storage of objects for the current request and the next request only. The subsequent request will clear the storage of any variables stored in the first
request. This is a convenience map that allows you to store information temporarily, which is very convenient when using redirection or chaining.
Example
flash['message'] = 'hello world!'
grailsApplication
Description
An instance of
org.codehaus.groovy.grails.commons.GrailsApplication that provides information about the grails application
Example
return [controllers : grailsApplication.controllers]
grailsAttributes
Description
An instance of
org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes that provides convenience methods for the current grails request
Example
def templateUri = grailsAttributes.getTemplateUri("myTemplate",request)
log
Description
An instance of the Log4J logger for the controller. Grails creates a log per controller, which you can call on at any time to perform logging. When configuring Log4J using WEB-INF/log4j.properties you should use properties of the form:
log4j.logger.TestController=debug, stdout
Where "TestController" is the fully qualified class name of your controller class.
Example
You simply use the standard Log4J logging methods:
log.trace('Doing something')
log.debug('Debug info here')
log.error('Something went wrong')
log.error('Something went wrong', someException)
params
Description
A map of the available request parameters and/or controller parameters
Example
def a = Account.get( params["id"] )
request
Description
The
HttpServletRequest instance for the request. Request attributes can be accessed with the Map syntax provided by groovy
In addition, Grails adds the following dynamic properties and methods to HttpServletRequest (
since 0.5.5):
- forwardURI - The original request URI, i.e. the one the user entered into their browser.
Example
request['anAttribute']
request.getHeader("user-agent")response
Description
The
HttpServletResponse instance
Example
response.setHeader("myheader", "myvalue")
servletContext
Description
The ServletContext instance as per the servlet API
Example
def myUrl = servletContext.getResource("/path/to/url")
session
Description
Provides access to a map of the HttpSession instance
Example
def loggedUser = session["loggedUser"]
Methods
bindData
Description
Binds data to a target instance performing type conversion if necessary. Useful for binding request parameters to properties of objects. Since 0.4 this has been modified to never assign values for the special ORM properties "id" or "version", nor the special Groovy properties (for Groovy classes) 'metaClass' and 'properties'. Note that this only operates on the top-level object currently, nested object id/version etc assignments must be suppressed explicitly using the "excludes" parameter.
Parameters
- target - The target object to bind to
- params - The parameters to bind to the target object
- excludes (optional) - A list of property names to exclude from the binding, with dot-notation support. Use to suppress values being assigned from form data.
- prefix (optional, since 0.5.5) - A string representing a prefix to use to filter the parameters. A prefix separater of "." is assumed e.g. author.name
Examples
bindData(target, this.params) // binds request parameters to a target object
bindData(target, this.params, ['firstName', 'lastName']) // exclude firstName and lastName (since 0.4)
bindData(target, this.params, "author") // only use parameters starting with "author." e.g. author.email (since 0.5.5)
bindData(target, this.params, ['firstName', 'lastName'], "author")
// exclude firstName and lastName and only use parameters starting with "author." e.g. author.email (since 0.5.5)
chain
Description
Chains the model (The model is retained from one action to the next) from one action to the next allowing you to build up the model from an action chain.
Parameters
- uri - The full uri to redirect to (example /book/list, book/show/2)
- controller - The controller to redirect to, defaults to the current controller if not specified
- action - The action to redirect to, either a string name or a reference to an action within the current controller
- id - The id to use in redirection
- model (required) - The model to chain to the next action
- params (optional) - Parameters to pass to the action chained to.
Examples
chain(action:"details",model:[book:new Book(title:'The Shawshank Redemption')])
getViewUri
Description
Retrieves the relative uri of a named view within the Grails application. If the view contains a '/' at the start it will be resolved relative to the views folder as a shared view otherwise it will be relative to the current controller
Parameters
- name (required) - The name of the view
Examples
assert getViewUri('myView') == /WEB-INF/grails-app/views/controllerName/myView.gsp
assert getViewUri('/mySharedView') == /WEB-INF/grails-app/views/mySharedView.gsp
getTemplateUri
Description
Retrieves the relative uri of a named template within the Grails application. If the template contains a '/' at the start it will be resolved relative to the views folder as a shared template otherwise it will be relative to the current controller
Parameters
- name (required) - The name of the template
Examples
assert getTemplateUri('myTemplate') == /WEB-INF/grails-app/views/controllerName/_myTemplate.gsp
assert getTemplateUri('/mySharedTemplate') == /WEB-INF/grails-app/views/_mySharedTemplate.gsp
redirect
Description
Redirects the current action to another action, optionally passing parameters and/or errors
Parameters
- uri - The full uri to redirect to (example /book/list, book/show/2)
- url - The absolute url to redirect to (example: "http://www.blogjava.net/BlueSUN")
- controller - The controller to redirect to, defaults to the current controller if not specified
- action - The action to redirect to, either a string name or a reference to an action within the current controller
- id - The id to use in redirection
- params - Parameters to pass to the action redirected to.
Examples
redirect(uri:"book/list")
redirect(url:"http://www.blogjava.net/BlueSUN")
redirect(action:"show")
redirect(controller:"book",action:"list")
redirect(action:"show",id:4, params:[author:"Stephen King"])
render
Description
A multi-purpose method for rendering responses to the client which is best illustrated with a few examples! Warning, as of Grails 0.5, this method does not always support multiple parameters. For example, if you specify both collection and model, the model parameter will be ignored.
Parameters
- text (optional) - The text to render
- builder (optional) - The builder to use when rendering markup
- view (optional) - The view to delegate the rendering to
- template (optional) - The template to render
- var (optional) - The name of the variable to be passed into a template, defaults to the groovy default argument 'it' if not specified
- bean (optional) - The bean to use in rendering
- model (optional) - The model to use in rendering
- collection (optional) - For rendering a template against each item in a collection
- contentType (optional) - The contentType of the response
- encoding (optional) - The encoding of the response
- converter (as single non-named first parameter) - A Converter that should be rendered as Response
Examples
// renders text to response
render "some text"// renders text for a specified content-type/encoding
render(text:"<xml>some xml</xml>",contentType:"text/xml",encoding:"UTF-8")// render a template to the response for the specified model
render(template:"book",model:[book:new Book(title:'The Shining',author:'Stephen King')])// render each item in the collection using the specified template
render(template:"book",collection:[b1, b2, b3])// render a template to the response for the specified bean
render(template:"book",bean:new Book(title:'The Shining',author:'Stephen King'))// render the view with the specified model
render(view:"viewName",model:[book:new Book(author:'Stephen King')])// render the view with the controller as the model
render(view:"viewName"
)
// render some markup to the response
render {
div(id:"myDiv", "some text inside the div")
}// render some XML markup to the response
render(contentType:"text/xml") {
books {
for(b in books) {
book(title:b.title,author:b.author)
}
}
}// render an OpenRico (http://www.openrico.org) response with the builder attribute:
def b = new Book(title:"Kiss the Girls", author:"James Patterson")
render(builder:"rico") {
object(id:"bookUpdater") {
book(title:b.title,author:b.author)
}
}// render a JSON ( http://www.json.org ) response with the builder attribute:
render(builder:"json") {
book(title:b.title,author:b.author)}// render a Converter which sets the appropriate Content-Type (text/json or text/xml)
// and don't forget to import the Converter -> import grails.converters.*
render Book.list(params) as JSON
render Book.get(params.id) as XMLdef converter = new Book(title: "The Definitive Guide to Grails") as JSON
render(converter)