Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'get' in an action for Grails controllers causes action to execute even when not called

Tags:

grails

Issue: A controller's action has a render tag without passing in a model. There exists an action that begins with the word 'get'.

grails-app/views/site/home.gsp:

homepage

SiteController.groovy:

class SiteController {

    def index() {
        render (view: "home")
    }

    def getTest() {
        render "getTest"
    }

}

The site is accessed at localhost:8080/site to execute the index action of SiteController.

Expected output: homepage Actual output: getTest homepage

If the render action of index is changed to this:

render(view: "home", model: [:])

The expected output is produced.

If a character is added before the word get in the action name, the expected output is produced.

Interestingly enough, getTest() is color coded as purple in IDEA. It should also be noted that if you have multiple methods with the word get at the beginning, they are ALL executed.

This did NOT happen in Grails 1.3.6. This is reproducible in a brand new Grails 2.2.2 project and seems like a bug to me. Why is this happening?

like image 653
user1661781 Avatar asked Jun 24 '13 16:06

user1661781


1 Answers

GRAILS-9310 suggests that this is a known limitation which won't be changed, the workaround is not to name your actions get*. The root cause is

If no explicit model is returned the controller's properties will be used as the model (Grails docs)

When you define a getTest() method this means that the controller has a test property, and when you render the "home" view without an explicit model the controllers properties get enumerated to form the model map. The getTest() method will be called as part of this enumeration process.

If you really need getTest to appear in the URL then you'll have to name the actual action something else and then define a custom URL mapping to direct the /controller/getTest URI to the renamed action.

like image 63
Ian Roberts Avatar answered Nov 15 '22 07:11

Ian Roberts