Saturday, June 05, 2010

Jersey JAX-RS and Freemarker


The example below uses sun specific packages. See here for how to do it using jax-rs stuff only.


I've been scratching around with various REST frameworks and I think I like Jersey. However, there's no native support out of the box for my fave templating superstar Freemarker.

So here's my first scratch at a ViewProcessor that supports Freemarker.

public class FreemarkerViewProcessor implements ViewProcessor<Template> {

private final Logger l = Logger.getLogger(FreemarkerViewProcessor.class);
private final Configuration cfg = new Configuration();

public void setServletContext(final ServletContext context) {
// TODO - all of these should be in
cfg.setTemplateLoader(new WebappTemplateLoader(context, "/WEB-INF/templates"));

public Template resolve(final String path) {
try {
return cfg.getTemplate(path);
} catch (final IOException e) {
return null;

public void writeTo(final Template template, final Viewable viewable, final OutputStream out) throws IOException {
try {
template.process((Map<String, Object>) viewable.getModel(), new OutputStreamWriter(out));
} catch (final TemplateException e) {
throw new IOException(e);

And here's how you use it...

public class BananaResource {

public Viewable getBanana() {
final Map<String, Object> vars = new HashMap<String, Object>();
vars.put("name", "banana");
return new Viewable("/banana.ftl", vars);