Search code examples
grailscontrollergsp

how to set a variable for application scope i.e. only 1 for entire application in grails controller


i want to set one variable for my entire application and i want to update it whenever a request comes in to a particular action

like

def action = {
    // some integer variable is already set in application scope with name variable
    variable++
    render(view:"action", model:[variable])
}

In Gsp

<html>
    <body>
        Variable is ${variable}
    </body>
</html>

The output would be

Variable is 1
// on subsequent requests
Variable is 2 and so on....

Thanks


Solution

  • Is it needs to be one across whole app?

    Its possible by using an (singleton) service, that will handle your value, like:

    class VariableService {
       int value
    
       synchronized int get() {
          return value
       }
    
       synchronized int inc(int value) {
          this.value += value
          return this.value   
       }
    
       synchronized void set(int value) {
          this.value = value
       }
    }
    

    and the use it where you need