Platinum Partner
java,groovy,tips and tricks

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

Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}