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.
/* 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 } } }


Paolo Foletto says:
Simply wonderful!
July 12, 2009, 11:07 amCHARLES says:
Excellent share. Thanks for informing us.
April 23, 2010, 8:04 pm