Grails - Controllers and Actions



Description

Controller is used for handling web requests along with some actions such as redirecting, rendering views etc. You can use the below command to create a controller in your project.

 
grails> create-controller [name]
Grails Controller Actions

After running the above command, it will create a controller in the grails-app/controllers/helloworld/MycontrollerController.groovy file.

 
package helloworld

class MycontrollerController {

    def index() { }
}

The helloworld is a name of an application and MycontrollerController maps to /Mycontroller URI by default.

Creating Actions

You can create actions for a controller which maps to an URI.

 
package helloworld

class MycontrollerController {

   def display() { 
	
      //logic for controller 
	   
      //creating model
	   
      return model	
   }
}

The above example maps to /Mycontroller/display URI. There are some rules to be followed when an action is requested for default URI.

  • It is said to be default, if there is only one action.

  • It can be default, if an action has name called "index".

  • You can use the defaultAction property to set it explicitly.

Advertisements