pri_dev pri_dev - 1 year ago 146
Groovy Question

Setting global variables and accessing them in Grails controllers

This may be a basic question but I am new to grails and tried looking for a solution.
I need to have a global variable in my groovy controller, a list for example, which is updated in one of the closures (def) and its value is updated in that def,
this new value for the list should be available in other closure/def.
I tried simply:

class MyController {
def myList = []

def def1 = { myList = someList.clone();}

def def2 = { println myList}

The value of
should be displayed as the updated value from
, right now it stays empty. Would
help? or is there a method to pass variables between closures directly, since I dont want the huge list to be passed to GSP and back in the second

Answer Source

Your controllers should stay stateless. Controllers are instantiated at each action request, so your member variable myList will be thrown away between actions. If you define it static, it will be shared by all instances of MyController.

If you define myList static, all clients accessing your controller will get the same result. If that's what you want, your list should probably be stored through domain objects in your database (see chapter 5 of Grails documentation, Object Relational Mapping).

If you want each client to have their own myList shared between controller actions, what you are looking for are called web flows. They provide a mechanism to store state between Controller actions performed by a given client. Web flows are documented in Grails documentation (Chapter 6 - The Web Layer).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download