Archive for August, 2009

GSP and JSP

Tuesday, August 18th, 2009

The question why Grails has GSP when there is JSP is a natural one. Here are a few substantial differences:

  1. A GSP allows the same ${…} expressions as in a Groovy GString. JSP EL expressions are restricted to object navigation, which is generally a good idea but can also make it difficult to access anything that isn’t a getter (e.g. String length()). JSTL functions provide some help but the more general case requires creating static helper methods, registering them through a taglib descriptor, adding a taglib declaration, and finally using the function.
  2. Using Groovy in logical and iterative tags comes with major perks such as the safe navigation operator: ${customer.phones?.size()} or the Elvis operator: ${totalCount ?: 10}.
  3. The ability to invoke Grails dynamic tags as methods makes it easier to produce well-formed markup:
    
    <!-- With a regular tag -->
    <a href="<g:createLink action="list" />">A dynamic link</a>
    
    <!-- As a method call -->
    <a href="${createLink(action:'list')}">A dynamic link</a>
    
  4. GSP provides a much simpler mechanism for creating and testing custom tag libraries in Groovy that does not require tld files and taglib declarations and of course uses Groovy. Here is a sample test case for a Grails tag library:
    import grails.test.*
    class CustomerTagLibTests extends TagLibUnitTestCase {
      void testRepeat() {
        tagLib.repeat(times: '2') {
          'output<br/>'
        }
        assertEquals 'output<br/>output<br/>', tagLib.out.toString()
      }
    }
    
  5. The Grails paginate tag. It is such a common need for web applications. In comparison to the Displaytag library I think the Grails paginate tag is more lightweight and more usable.