Search

Dark theme | Light theme

August 14, 2013

Grails Goodness: Using the header Method to Set Response Headers

Grails adds a couple of methods and properties to our controller classes automatically. One of the methods is the header() method. With this method we can set a response header with a name and value. The methods accepts two arguments: the first argument is the header name and the second argument is the header value.

In the following controller we invoke the header() method to set the header X-Powered-By with the Grails and Groovy version.

package header.ctrl

class SampleController {

    def grailsApplication

    def index() {
        final String grailsVersion = grailsApplication.metadata.getGrailsVersion()
        final String groovyVersion = GroovySystem.version
        header 'X-Powered-By', "Grails: $grailsVersion, Groovy: $groovyVersion"
    }

}

We can test this with the following Spock specification:

package header.ctrl

import grails.test.mixin.TestFor
import spock.lang.Specification

@TestFor(SampleController)
class SampleControllerSpec extends Specification {

    def "index must set response header X-Powered-By with value"() {
        when:
        controller.index()

        then:
        response.headerNames.contains 'X-Powered-By'
        response.header('X-Powered-By') == 'Grails: 2.2.4, Groovy: 2.0.8'
    }

}

Code written with Grails 2.2.4