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 :

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

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

WebAttributes

[java]
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")
}
}
[/java]

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.

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

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

ResponseRedirector

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

[/java]

RequestForwarder

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

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *