Monday, February 22, 2010

Grails Goodness: Type Conversion on Parameters

With Grails we get a lot of extra support for handling request parameters. We can convert a request parameter value to a specific type with a simple method invocation. Grails adds for example the method int() to the parameter so we can return the request parameter value converted to an int. Grails adds several methods like byte(), long(), boolean() we can use in our code. And since Grails 2.0 also support for dates.

Update: it is also possible to get the values from request parameters with the same name.

class SimpleController {
    def submit = {
        def intValue = params.int('paramInt')
        def shortValue = params.short('paramShort')
        def byteValue = params.byte('paramByte')
        def longValue = params.long('paramLong')
        def doubleValue = params.double('paramDouble')
        def floatValue = params.float('paramFloat')
        def booleanValue = params.boolean('paramBoolean')
        [ intValue: intValue, shortValue: shortValue, 
          byteValue: byteValue,
          longValue: longValue, doubleValue: doubleValue, 
          floatValue: floatValue, booleanValue: booleanValue ]

We can run the following testcase to test the various parameter types and values.

import grails.test.*

class SimpleControllerTests extends ControllerUnitTestCase {
    void testParams() {
        controller.params.paramInt = '42'
        controller.params.paramShort = '128'
        controller.params.paramByte = '8'
        controller.params.paramLong = '90192'
        controller.params.paramDouble = '12.3'
        controller.params.paramFloat = '901.22'
        controller.params.paramBoolean = 'true'

        def result = controller.submit()
        assertEquals 42, result.intValue
        assertEquals 128, result.shortValue
        assertEquals 8, result.byteValue
        assertEquals 90192L, result.longValue
        assertEquals 12.3, result.doubleValue
        assertEquals 901.22f, result.floatValue
        assertTrue result.booleanValue
    void testInvalidParams() {
        controller.params.paramInt = 'test'

        def result = controller.submit()
        assertNull result.intValue
    void testBooleanParam() {
        controller.params.paramBoolean = 'false'
        def result = controller.submit()
        assertFalse result.booleanValue


Roshan Shrestha said...

Is there any differences or advantage over using "as" operator, e.g.

params['paramsInt'] as int

mrhaki said...

@Roshan Shrestha: There is no difference, just another way to do the same thing.

Anonymous said...

Pity they didn't include a params.date(date, format)

Post a Comment