Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Grails Goodness: Using the header Method to Set Response Headers

DZone's Guide to

Grails Goodness: Using the header Method to Set Response Headers

· Java Zone
Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}