|Home > FAQs > Cookbook > GroovyResult|
This is an attempt to create a Result type that uses Groovy (http://groovy.codehaus.org) files as a view. It exposes the current ActionContext to a groovy script. This doesn't really have much practical use, but it's fun nonetheless and shows how easy it is to create a Result. There is another Result (JFreeChartResult) in the Cookbook
Not much - just make sure you have Groovy in your classpath, and the antlr, asm-* and groovy jars available to your webapp.
xwork.xml - action definitions
The result type takes one parameter (for now), namely 'file', which contains the name of the groovy script in our script directory.
Here's the code of the actual GroovyResult. This is a verbose version, with a lot of error checking.
The first part of the result is little more than:
A Binding object allows us to 'bind' objects to a groovy script, so they can be used as variables. In this case, I took the ActionContext and exposed it as 'context'.
We also bind an OutputStream to the groovy script (as 'out') - it simply serves as a replacement for the standard System.out, so any printing goes directly to the http response outputstream.
Next step; we create a GroovyShell, and pass our populated Binding to the constructor. Any script ran by this shell will have access to the passed variables (ActionContext and OutputStream).
Before you can run a groovyFile, you need to parse it. Any syntax errors will be reported here - I also suggest adding a better error reporting in this case if you actually want to use this Result.
Upon successful parsing, a Script is returned (which could be cached if you want to increase performance) which will be run by our Shell.
As a test, you might want to create a little 'groovy' script to test our Result.
test.groovy - a simple groovy script
Place the test.groovy file in your groovy scripts directory. You should now see the result when you invoke MyAction.action in your browser.
Possible improvements are binding all objects on the stack so they become available to the groovy script, refactoring to an InputStream instead of a File, etc .. Comments welcome !