Search

Dark theme | Light theme
Showing posts with label GrailsGoodness:Request. Show all posts
Showing posts with label GrailsGoodness:Request. Show all posts

July 8, 2014

Grails Goodness: Enable Accept Header for User Agent Requests

Especially when we use Grails to create a RESTful API we want to enable the request header Accept, so Grails can do content negotiation based on the value in the header. For example we could use the request header Accept: application/json to get a JSON response. Grails will look at the boolean configuration property grails.mime.use.accept.header to see if the Accept header must be parsed. The default value is true so the Accept header is used. But there is another property which determines if the Accept header is used: grails.mime.disable.accept.header.userAgents. The value must contain a list or a regular expression pattern of user agents which are ignored for the Accept header. The default value is ~/(Gecko(?i)|WebKit(?i)|Presto(?i)|Trident(?i))/. So for any request from these user agents, mostly our web browser, the Accept header is ignored.

If we use REST web services test tools from our browser, for example Postman, then any Accept header we set in the tool is ignored by Grails. We must change the value of the configuration property grails.mime.disable.accept.header.userAgents to for example an empty list. Then we know for every request send to our Grails application, either from a web browser or command-line tool like curl, the Accept header is interpreted by Grails.

The following sample shows how we make sure the Accept header is always used:

// File: grails-app/conf/Config.groovy
...
grails.mime.use.accept.header = true // Default value is true.
grails.mime.disable.accept.header.userAgents = []
...

Written with Grails 2.4.1.

March 10, 2010

Grails Goodness: Get Values from Parameters with Same Name

Grails supports type conversion on request parameters. But it is also easy to handle multiple request parameters with the same name in Grails. We use the list() method on the params and we are sure we get back a list with values. Even if only one parameter with the given name is returned we get back a list.

// File: grails-app/controllers/SimpleController.groovy
class SimpleController {

    def test = {
        // Handles a query like 'http://localhost:8080/simple?role=admin&role=user'
        def roles = params.list('role')
        render roles.join(',')  // Returns admin,user
    }

}