DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Convert HTML to DOCX in Java
  • Reading an HTML File, Parsing It and Converting It to a PDF File With the Pdfbox Library
  • Introduction To Template-Based Email Design With Spring Boot
  • How to Convert Excel and CSV Documents to HTML in Java

Trending

  • Comparing SaaS vs. PaaS for Kafka and Flink Data Streaming
  • Scalability 101: How to Build, Measure, and Improve It
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Scalable System Design: Core Concepts for Building Reliable Software
  1. DZone
  2. Coding
  3. Languages
  4. Java HTML Templating With Handlebars and Undertow

Java HTML Templating With Handlebars and Undertow

Are you a Java programmer who wants to make a website? Good news! With Handlebars, you can create a site designed with the Java programming language.

By 
Bill O'Neil user avatar
Bill O'Neil
·
Jun. 09, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
8.2K Views

Join the DZone community and get the full member experience.

Join For Free

Researching how to create a website in Java can be a daunting task. A few Google searches and you end up with tons of libraries and strong opinions. JSP, JSF, Spring MVC, GWT, Vaadin and many more. All of them seem like they have quite a 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 an HTML templating engine. Enter Handlebars - a perfect, fairly simple syntax added to plain HTML anyone should be able to pick up immediately (Yes, MVC frameworks can use this also, but do we need a framework for what a single class can do?). It also conveniently 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 an HTML templating library to solve a similar problem.

public class Templating {
    private static final Logger log = LoggerFactory.getLogger(Templating.class);

    // Once again using static for convenience use your own DI method.
    private static final Templating DEFAULT;
    static {
        Templating.Builder builder =
            new Templating.Builder()
                          .withHelper("dateFormat", TemplateHelpers::dateFormat)
                          .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, Object data) {
        String response = renderTemplate(templateName, data);
        return compressor.compress(response);
    }

    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, Object data) {
        String response = renderRawTemplate(rawTemplate, data);
        return compressor.compress(response);
    }

    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 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);
        }
    }
}

View on GitHub

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));
}

View on GitHub

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();
}

View on GitHub

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);
}

View on GitHub

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);
}

View on GitHub

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);
}

View on GitHub

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 from 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. In later examples, we can get into using Webpack to manage HTML/CSS/JS.

HTML Java (programming language) Template

Published at DZone with permission of Bill O'Neil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • How to Convert HTML to DOCX in Java
  • Reading an HTML File, Parsing It and Converting It to a PDF File With the Pdfbox Library
  • Introduction To Template-Based Email Design With Spring Boot
  • How to Convert Excel and CSV Documents to HTML in Java

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: