Previously on Handling Content Types with Undertow we showed how to send a simple HTML response. That is a little too basic for our use case. However, JSP, JSF, Spring MVC... all seem like they have a bit of learning curve. All we really need is to pass an object to a template and render some HTML, nothing fancy. Let's take this a step further and follow the node / express approach of simply plugging in a HTML templating engine. Enter Handlebars, perfect, fairly simple syntax added to plain HTML anyone should be able to pick this up immediately (Yes MVC frameworks can use this also but do we need a framework for what a single class can do?). It also convienetly has ports in many languages. This means we can use the same templates client side (javascript) and server side if we want.

HTML Templating Utility

This is a rare case where we decided to make a simple abstraction hiding the underlying jknack handlebars implementation. Since it only really needs a few methods we can hide the implementation and easily swap it out later. Notice how we have a few config options. When we are running locally we want handlebars templates to be compiled on the fly and NOT cached. We also utilize HTML compression for all of the HTML specific methods. We also offer some non HTML templating methods. Sometimes it might make sense to abuse a HTML templating library to solve a similair problem.

public class Templating {
    private static final Logger log = LoggerFactory.getLogger(Templating.class);
    private static final Map<Object, Object> NO_DATA = Maps.newHashMapWithExpectedSize(0);

    // Once again using static for convenience use your own DI method.
    private static final Templating DEFAULT;
    static {
        Templating.Builder builder =
            new Templating.Builder()
                          .withHelpers(new TemplateHelpers())
                          .withHelper("md", new MarkdownHelper())
                          .withHelper(AssignHelper.NAME, AssignHelper.INSTANCE)
                          .register(HumanizeHelper::register);
        // Don't cache locally, makes development annoying
        if (Env.LOCAL != Env.get()) {
            builder.withCaching()
                   .withResourceLoaders();
        } else {
            String root = AssetsConfig.assetsRoot();
            builder.withLocalResourceLoaders(root);
        }
        DEFAULT = builder.build();
    }

    public static Templating instance() {
        return DEFAULT;
    }

    private final Handlebars handlebars;
    private final HtmlCompressor compressor = new HtmlCompressor();
    Templating(Handlebars handlebars) {
        this.handlebars = handlebars;
    }

    public String renderHtmlTemplate(String templateName) {
        return renderHtmlTemplate(templateName, NO_DATA);
    }

    public String renderHtmlTemplate(String templateName, Object data) {
        String response = renderTemplate(templateName, data);
        return compressor.compress(response);
    }

    public String renderTemplate(String templateName) {
        return renderTemplate(templateName, NO_DATA);
    }

    public String renderTemplate(String templateName, Object data) {
        Template template;
        try {
            template = handlebars.compile(templateName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return render(template, data);
    }

    public String renderRawHtmlTemplate(String rawTemplate) {
        return renderRawTemplate(rawTemplate, NO_DATA);
    }

    public String renderRawHtmlTemplate(String rawTemplate, Object data) {
        String response = renderRawTemplate(rawTemplate, data);
        return compressor.compress(response);
    }

    public String renderRawTemplate(String rawTemplate) {
        return renderRawTemplate(rawTemplate, NO_DATA);
    }

    public String renderRawTemplate(String rawTemplate, Object data) {
        Template template;
        try {
            template = handlebars.compileInline(rawTemplate);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return render(template, data);
    }

    private String render(Template template, Object data) {
        try {
            // Can't currently get the jackson module working not sure why.
            Map<String, Object> jsonMap = Json.serializer().mapFromJson(Json.serializer().toString(data));
            if (log.isDebugEnabled()) {
                log.debug("rendering template " + template.filename() + "\n" + Json.serializer().toPrettyString(jsonMap));
            }
            return template.apply(jsonMap);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    static class Builder {
        private final Handlebars handlebars = new Handlebars();
        private final List<TemplateLoader> loaders = Lists.newArrayList();
        public Builder() {

        }

        public Builder withResourceLoaders() {
            log.debug("using resource loaders");
            loaders.add(new ClassPathTemplateLoader());
            loaders.add(new ClassPathTemplateLoader(TemplateLoader.DEFAULT_PREFIX, ".sql"));
            return this;
        }

        public Builder withLocalResourceLoaders(String root) {
            log.debug("using local loaders");
            loaders.add(new FileTemplateLoader(root));
            loaders.add(new FileTemplateLoader(root, ".sql"));
            return this;
        }

        public Builder withCaching() {
            log.debug("Using caching handlebars");
            handlebars.with(new ConcurrentMapTemplateCache());
            return this;
        }

        public <T> Builder withHelper(String helperName, Helper<T> helper) {
            log.debug("using template helper {}" , helperName);
            handlebars.registerHelper(helperName, helper);
            return this;
        }

        public <T> Builder withHelpers(Object helpers) {
            log.debug("using template helpers {}" , helpers.getClass());
            handlebars.registerHelpers(helpers);
            return this;
        }

        public <T> Builder register(Consumer<Handlebars> consumer) {
            log.debug("registering helpers");
            consumer.accept(handlebars);
            return this;
        }

        public Templating build() {
            handlebars.with(loaders.toArray(new TemplateLoader[0]));
            return new Templating(handlebars);
        }
    }
}

Undertow HTML Templating Sender

A few simple lines and we can now send HTML templates with Undertow.

default void sendRawHtmlTemplate(HttpServerExchange exchange, String rawTemplate, Object data) {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
    exchange.getResponseSender().send(Templating.instance().renderRawHtmlTemplate(rawTemplate, data));
}

default void sendHtmlTemplate(HttpServerExchange exchange, String templateName, Object data) {
    exchange.getResponseHeaders().put(Headers.CONTENT_TYPE, "text/html");
    exchange.getResponseSender().send(Templating.instance().renderHtmlTemplate(templateName, data));
}

Undertow HTML Templating Server

Routes for the Handlers below.

private static final HttpHandler ROUTES = new RoutingHandler()
    .get("/messageRawTemplate", HandlebarsHandlers::messageRawTemplate)
    .get("/messagesRawTemplate", HandlebarsHandlers::messagesRawTemplate)
    .get("/messagesTemplate", HandlebarsHandlers::messagesTemplate)
;

public static void main(String[] args) {
    SimpleServer server = SimpleServer.simpleServer(ROUTES);
    server.start();
}

Undertow HTML Templating Handlers

Simple Raw Handlebars HTML Template

Simple inline Java Handlebars template with variable substitution.

private static final String messageTemplate = "<p>hello {{message}}</p>";
public static void messageRawTemplate(HttpServerExchange exchange) {
    String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world");
    Map<String, Object> data = Maps.newHashMap();
    data.put("message", message);
    Exchange.body().sendRawHtmlTemplate(exchange, messageTemplate, data);
}
curl localhost:8080/messageRawTemplate?message=StubbornJava
<p>hello StubbornJava</p>

Iterating Raw Handlebars HTML Template

Simple inline Java Handlebars template with iteration substitution.

private static final String messagesTemplate = "{{#each messages}}<p>Hello {{.}}</p>{{/each}}";
public static void messagesRawTemplate(HttpServerExchange exchange) {
    String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world");
    int num = Exchange.queryParams().queryParamAsInteger(exchange, "num").orElse(5);
    List<String> messages = Lists.newArrayList();
    for (int i = 0; i < num; i++) {
        messages.add(message + " " + i);
    }
    Map<String, Object> data = Maps.newHashMap();
    data.put("messages", messages);
    Exchange.body().sendRawHtmlTemplate(exchange, messagesTemplate, data);
}
curl 'localhost:8080/messagesRawTemplate?message=StubbornJava&num=3'
<p>Hello StubbornJava 0</p><p>Hello StubbornJava 1</p><p>Hello StubbornJava 2</p>

Handlebars HTML Template with CSS

Java Handlebars template from resource files with layout, includes, and iteration. Now this is starting to look like a real website. Find the templates here.

public static void messagesTemplate(HttpServerExchange exchange) {
    String message = Exchange.queryParams().queryParam(exchange, "message").orElse("world");
    int num = Exchange.queryParams().queryParamAsInteger(exchange, "num").orElse(5);
    List<String> messages = Lists.newArrayList();
    for (int i = 0; i < num; i++) {
        messages.add(message + " " + i);
    }
    Map<String, Object> data = Maps.newHashMap();
    data.put("messages", messages);
    Exchange.body().sendHtmlTemplate(exchange, "examples/handlebars/messages", data);
}
curl 'localhost:8080/messagesTemplate?message=StubbornJava&num=3'
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"/> <meta http-equiv="x-ua-compatible" content="ie=edge"/> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/> <title>Messages Demo</title> </head> <body> <nav class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand logo" href="/">Demo</a> </div> </div> </nav> <div class="container"> <p>Hello StubbornJava 0</p><p>Hello StubbornJava 1</p><p>Hello StubbornJava 2</p> </div> <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </body> </html>

These examples are better to clone the repo and run locally. The HTML compression will smash everything on one line. The final example includes all CSS / JS from bootstrap using the public CDN. To take this a step further you can integrate with webpack and npm to manage your javascript and assets. If you are not a strong HTML / CSS developer consider using a site template to make your website stand out.