mscharhag, Programming and Stuff;

A blog about programming and software development topics, mostly focused on Java technologies including Java EE, Spring and Grails.

Wednesday, 28 August, 2013

Assigning boolean values in Groovy Server Pages (GSP)

In my first blog post I want to point out a common pitfall for developers who are new to Groovy Server Pages (GSP).

Today I found the following code construct within a GSP file:

<g:set var="isAnchor" value="false" />
<g:if test="${ isAnchor }">

Other than expected the condition of the <g:if /> tag always evaluates to true.
The reason for this is that

<g:set var="isAnchor" value="false" />

assigns the string "false" to isAnchor and not the boolean value false. In Groovy a string (and GString) evaluates to true if it is not empty. "false" is not empty so the if condition always evaluates to true.
This issue can easily be fixed by assigning a boolean value to isAnchor instead of a string:

<g:set var="isAnchor" value="${ false }" />

An alternative (but not so clean) solution would be to change the condition to

<g:if test="${ isAnchor.toBoolean() }">

The groovy string method toBoolean() converts the string value to a boolean value.

The toBoolean() documentation says: If the trimmed string is "true", "y" or "1" (ignoring case) then the result is true otherwise it is false.


  • FiNaLsPY - Wednesday, 26 February, 2014

    You didn't mention the driver version you were using.

    I think think it was intended as you use de remove(query) method which is equivalent to :
    find(query) then for each result remove(_id)
    With null parameter it's like a find({}) which matches everything.
    Thus it'll end up deleting the whole bucket.

    anyway in the latest driver null argument is forbidden for a remove on gridfs
    See :

Leave a reply