Scriptlets in CF Anyone?

My last post about Comparators via CF Groovy was simplistic in nature, but the underlying concept is incredibly powerful.  Here's a similar snippet (from the demo app), this time using a Comparator class:

Collections.sort(variables.a, new ReverseDateKeyComparator())

So what do we have here?  Why it's a snippet of Java embedded directly in your CFML page, and it gets dynamically compiled and executed just like the CFML.  Let me say that again: it's a snippet of Java embedded directly in your CFML page.  It's even better than that, though, because it's Groovy, which is Java plus a whole lot more.

In addition to the scriptlet functionality, CF Groovy provides a classloading framework for Groovy scripts and classes, in addition to the ones provided by the CFML runtime and the JVM.  You can define an extra Groovy classpath for your scriptlets like this:

<g:setPath path="#expandPath('/groovy')#,#expandPath('/packages')#" />

There's no way to tell how the ReverseDateKeyComparator class in the first example is implemented, but it happens to be a Groovy class that I've added to the classpath with the <g:setPath> tag.  That class, just like the scriptlet, is dynamically compiled and executed just like the CFML.  This is also very powerful, because it eliminates the compile/build/deploy cycle that is usually required for Java code in a JEE environment.

Combining these two, you can use <g:script> to execute arbitrary scripts from the Groovy classpath, instead of inlining them:

<g:script name="myScript.groovy" />

This lets you reuse scripts across CFML pages, as well as reusing classes between scripts.

I've added CF Groovy to my Projects page, so that's the place for the latest info, as well as some documentation and the all-important Subversion information.

3 responses to “Scriptlets in CF Anyone?”

  1. Derek P.

    I find what you are doing here with Groovy and CF really truly interesting. I wish that more CF developers were more interested in the capabilities that languages like Groovy and JRuby offer them as far as interoperability is concerned. Groovy has always interested me and its adoption I find it surprising that its adoption is so slow.

    Great work here, this is very interesting work you are doing!

  2. Peter Bell

    Yeah, I've been surprised at the conferences I've attended (non-CF) that there seems to be more interest i JRuby than Groovy for the "dynamic fringes" of the Java community. Maybe it's just because Groovy had a slow initial adoption, but some of the new features are incredibly interestig (in the latest beta you can perform operations directly on the AST – talk about metaprogramming!) and I'm looking forward to doing more with Groovy.

    That said, I'm also hoping for a complete CF Script syntax, more performant object creation in CF and tighter integration with Hibernate to make more "hard things easy". I'd hate to see CF purely relegated to a set of jsp style view tags.