Grails - Controllers and Actions



Description

You can use the scopes for storing the variables. The below list shows available scopes to the controllers:

  • servletContext: It is an instance of ServletContext which allows to share the state of the web application.

  • session: It is an instance of HttpSession which associates with user state and connects a session with a client by using cookies.

  • request: It is an instance of HttpServletRequest which stores the object for the current request only.

  • params: These are the POST parameters or incoming request query string of mutable map.

  • flash: It can be used as temporary store that provides the attributes for the given request.

Accessing Scopes

The above variables can be used along with Groovy's array index operator to access the scopes.

For instance:

class HelloController {

   def find() 
   { 
      def findBy = params["findBy"]
      def loggedUser = session["logged_user"]
   }
}

The above values can be accessed within scopes by using the de-reference operator as shown below:

class HelloController {

   def find() 
   { 
      def findBy = params.findBy
      def loggedUser = session.logged_user
   }
}

The flash scope (temporary store that provides the attributes for the given request) can be used for displaying message before redirecting.

For instance:

class HelloController {

   def delete_info() 
   { 
     def info = Team.get(params.id)
        if (!info) {
           flash.message = "Sorry..No user found the id : ${params.id}"
           redirect(action:list)
        }
    // other code 
   }
}

The message value of the scopes can be used to display the message when you request the delete_info action and will be removed from the flash scope after the second request.

There are some supported controller scopes available in the Grails:

  • prototype (default): It is a default scope which creates a new controller for each request.

  • session: It uses the single controller for the scope of a user session.

  • singleton: It provides the only one instance of the controller and it is recommended for actions as methods.

You can add the static scope property to the class along with the above specified scope values to enable the scope.

static scope = "singleton"
Advertisements