Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails controller methods

Tags:

grails

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?
like image 354
Dónal Avatar asked Aug 30 '09 19:08

Dónal


2 Answers

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.

like image 108
Ted Naleid Avatar answered Nov 15 '22 07:11

Ted Naleid


'id' comes from UrlMappings entries such as "/$controller/$action?/$id?" - see http://docs.grails.org/latest/guide/single.html#urlmappings 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}".

like image 24
Burt Beckwith Avatar answered Nov 15 '22 05:11

Burt Beckwith