Traits Provided by Grails 3

03 / Jun / 2015 by pulkit 0 comments

The Core API’s in Grails 3 are based on Groovy Traits. Following are the few of the examples which shows the way you can use these traits in Groovy classes.

ResponseRenderer

With the help of ResponseRenderer traits we can provide render method to a Groovy class in the following way :

import grails.artefact.controller.support.ResponseRenderer
class ResponseRendererComponent implements ResponseRenderer {
    ResponseRendererComponent() {
        render "rendering from the constructor"
    }
}

Now when we try to instantiate ResponseRendererComponent, the render() inside the the constructor (which is provided by ReponseRenderer trait) will render the response.

WebAttributes

import grails.artefact.controller.support.ResponseRenderer
import grails.web.api.WebAttributes
class WebAttributesComponent implements WebAttributes, ResponseRenderer {
    WebAttributesComponent() {
        render "base url: ${webRequest.baseUrl}"
        render "<br>"
        render "params: ${params}"
        render "<br>"
        render grailsApplication.config.getProperty("myVar")
    }
}

In the above example we are accessing params, webRequest and properties which are defined in application.yml

ServletAttributes

With the help of SevletAttributes trait we can access the sessions inside any Groovy class.

import grails.artefact.controller.support.ResponseRenderer
import grails.web.api.ServletAttributes
class ServletAttributeComponent implements ServletAttributes, ResponseRenderer {
    ServletAttributeComponent() {
        render session.mySession
    }
}

We can also redirect and forward to an action of the controller from any Groovy class using ResponseRedirector and RequestForwarder traits.

ResponseRedirector

import grails.artefact.controller.support.ResponseRedirector
class ResponseRedirectorComponent implements ResponseRedirector {
    ResponseRedirectorComponent() {
        redirect(controller: "responseRedirector", action: "redirected")
    }
}

RequestForwarder

import grails.artefact.controller.support.RequestForwarder
class RequestForwarderComponent implements RequestForwarder {
    RequestForwarderComponent() {
        forward(controller:"requestForwarder",action:"forwarded")
    }
}

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -