Hacking WebWork Result Types: Freemarker to HTML to JavaScript

I threw all of my past experience with Struts out the window when I started my new job because we use WebWork. WebWork is approximately one thousand times better though so I’m not complaining. One of the unique to WebWork features (as compared to Struts) is the notion of a result type which is the process responsible for combining the model with a some kind of template (usually JSP or FreeMarker) to create a view.

Anyway, for various reasons we’ve found it useful at work to output some pieces of content usually rendered as HTML instead as JavaScript via document.write(). Because it would be a nightmare to maintain two FreeMarker templates, one for HTML and one for JavaScript output, I figured out a way to transform a FreeMarker template that normally renders HTML to render JavaScript using a custom WebWork result type. Simply extend the FreemarkerResultdoExecute() method with code that will look extremely similar to the existing doExecute() method. I’ll highlight the differences by showing you two lines from the existing doExecute() method:

// Process the template
template.process(model, getWriter());

and then the updated version that transforms the HTML into JavaScript using the StringEscapeUtils class from the commons lang library:

// Process the template
StringWriter writer = new StringWriter();
template.process(model, writer);
getWriter().write("document.write('" + StringEscapeUtils.escapeJavaScript(writer.toString()) + "')");

The xwork config file changes a bit as well. Here’s both the HTML version and the JavaScript version:

<result name="html" type="freemarker">foo.ftl</result>
<result name="javascript" type="freemarkerhtml2javascript">
  <param name="location">foo.ftl</param>
  <param name="contentType">text/javascript</param>
</result>

The end result is that with a little logic added to your WebWork action, you can include the result of that action in your own site:

<ww:action name="viewSnippet" executeResult="true" />

and enable other people to use the same result via embedded JavaScript:

<script src="http://yoursite.com/yourSnippet.jspa?format=javascript"></script>

One thought on “Hacking WebWork Result Types: Freemarker to HTML to JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>