Grails controller methods

Tag: grails Author: dn1234 Date: 2009-08-14

Many of the available controller methods (chain, forward, redirect) take a map which can include keys such as:

  • id
  • params
  • model

A couple of questions about these:

  • Is 'id' just an alias for a request parameter named 'id'? In other words, is there any difference between:

chain(controller: "member", action: "showProfile", params: [id: memberId])

and

chain(controller: "member", action: "showProfile", id: memberId)

  • The chain method (possibly among others) allows passing a model and/or params (map) from controller action A to B. Practically speaking, what's the difference between passing data from action A to B via the params and model maps? Also, if the data is passed in the model map, how do I access it in controller action B?

Other Answer1

Everything Burt said is correct. In addition, the reason that you'd want do do a chain (if you have a model) or a redirect (if you don't have a model to keep) is because both of those methods return a 302 redirect response to the browser. The browser then knows to ask for the next page.

It then has the correct url in the header for the resulting page, rather than the url from the page where the original request was from.

This pattern is very useful after a POST of information as it avoids all kinds of trouble with bookmarking, and resubmitting of information if the user hits refresh on the resulting page.

Ex: if you're saving a Book and you want to render the list page if the book is successfully saved. If you just call "controller.list()" in your method, it will show the user the list of books that gets rendered, but the url bar will still say ".../book/save". This is not good for bookmarking or reloading. Instead, calling redirect/chain will send the 302 response to the browser telling it to ask for the ".../book/list" page, which it does. All of your variables (your model and other flash messages) are in flash scope so they're still available to your model/view to use and everything is happy in the world.

This pattern is called Post/Redirect/Get.

Other Answer2

'id' comes from UrlMappings entries such as "/$controller/$action?/$id?" - see http://grails.org/doc/1.1.x/guide/6.%20The%20Web%20Layer.html#6.4%20URL%20Mappings for usage.

Params are querystring parameters or form post parameters, accessed in non-Grails apps using "request.getParameter('foo')" but simplified in Grails as "params.foo". The contents of the model map are stored in the Request as attributes, accessed in non-Grails apps using "request.getAttribute('foo')" but simplified in Grails as "request.foo" or more typically accessed directly in GSPs, e.g. "${foo}".

comments:

I had a look at the docs and it seems as though id is in fact a request parameter, i.e. you would access it in a controller using params.id. Is that consistent with your understanding?