RSS

Archive for the ‘Grails’ Category

Grails controller actions behind the scenes

Monday, January 24th, 2011

All controller actions in grails magically have access to request, params, session and bunch of other utility methods such as redirect, render etc. I digged through the grails source to find how it is done. The functionality is added to controller meta-classes utilizing groovy’s meta-programming capabilities. It is written as a plugin where in all the controller meta-classes are attached the functionality we all see. Here is the portion of code that adds some functionality. Imagine writing an action/controller in conventional j2ee style, this small portion of elegant code gets rid of all the boiler plate repetitive code. This simple example shows the power of meta programming. Kudos to all the contributors for this excellent project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
The method below is called for controller meta classes. and RCH is the RequestContenxtHolder from spring MVC
import org.springframework.web.context.request.RequestContextHolder as RCH
*/
def registerCommonWebProperties(MetaClass mc, GrailsApplication application) {
        def paramsObject = {->
            RCH.currentRequestAttributes().params
        }
        def flashObject = {->
            RCH.currentRequestAttributes().flashScope
        }
        def sessionObject = {->
            RCH.currentRequestAttributes().session
        }
        def requestObject = {->
            RCH.currentRequestAttributes().currentRequest
        }
        def responseObject = {->
            RCH.currentRequestAttributes().currentResponse
        }
        def servletContextObject = {->
            RCH.currentRequestAttributes().servletContext
        }
        def grailsAttrsObject = {->
            RCH.currentRequestAttributes().attributes
        }
        // the params object
        mc.getParams = paramsObject
        // the flash object
        mc.getFlash = flashObject
        // the session object
        mc.getSession = sessionObject
        // the request object
        mc.getRequest = requestObject
        // the servlet context
        mc.getServletContext = servletContextObject
        // the response object
        mc.getResponse = responseObject
        // The GrailsApplicationAttributes object
        mc.getGrailsAttributes = grailsAttrsObject
        // The GrailsApplication object
        mc.getGrailsApplication = {-> RCH.currentRequestAttributes().attributes.grailsApplication }
        mc.getActionName = {->
            RCH.currentRequestAttributes().actionName
        }
        mc.getControllerName = {->
            RCH.currentRequestAttributes().controllerName
        }
    }
}

More about this here: http://satish.name/?p=24