Spark + Freemarker basic example

Today, we are going to develop a little web page with a form using Spark and Freemarker. The purpose is simply to know how they are used together and how to manage GET and POST request. In addition, I am going to add Bootstrap to learn how to combine Freemarker with CSS.

As its web page describes “Spark – A tiny Sinatra inspired framework for creating web applications in Java 8 with minimal effort“. You can see a previous example I implemented in this blog called: Quick REST demo with Spark.

In the same way, as its web page describes “FreeMarker is a “template engine”; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates

The project has these requirements:

  • JDK 8
  • Maven
  • IDE. I have used IntelliJ IDEA CE, but you can use NetBeans, Eclipse or your favorite one.

The final structure for our project will be:

./pom.xml
./src/main/java/com/wordpress/binarycoders/SayMyName.java
./src/main/resources/css/bootstrap.css
./src/main/resources/templates/form.ftl
./src/main/resources/templates/result.ftl

The first step is to create a simple maven java project, obtaining in this way a pom.xml and a basic project structure. We should assign groupId, artifactId and version.

After that, we should edit our pom.xml file to add the dependencies that we are going to use to implement our example:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.1</version>
</dependency>

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.22</version>
</dependency>

As I have said at the beginning of this post, Freemarker is a template engine, then, the next step is to write the templates. We are going to write two templates:

  • form.ftl: This is going to be the first page of our application and it is going to show us a form to introduce “user” and “email“.
  • result.ftl: This page is going to show us the information introduced in the form.

The first template: form.ftl

<html>
    <head>
        <title>Welcome</title>

        <link href="css/bootstrap.css" rel="stylesheet" />
    </head>
    <body>
        <form class="form-inline" method="POST" action="/sait">
            <div class="form-group">
                <label for="name">Name</label>
                <input type="text"
                       class="form-control"
                       id="name"
                       name="name"
                       placeholder="John Doe">
            </div>
            <div class="form-group">
                <label for="email">Email</label>
                <input type="email"
                       class="form-control"
                       id="email"
                       name="email"
                       placeholder="john.doe@example.org">
            </div>
            <button type="submit" class="btn btn-default">Send invitation</button>
        </form>
    <body>
</html>

The second template: result.ftl

<html>
    <head>
        <title>Said</title>
    </head>
    <body>
        <h1> Your name is ${name}</h1>
        <br>
        <h1> Your email is ${email}</h1>
    </body>
</html>

It is very important to remember in this point that to be allowed to recover our form parameters in the Java code we need to add the name attribute to our inputs. It is not enough with the id attribute.

In this point, we should add Bootstrap CSS file to our project.

And finally, we need to implement our main class that it is going to process the GET and the POST requests.

package com.wordpress.binarycoders;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.Version;
import spark.Spark;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

public class SayMyName {

    public static void main(String[] args) {
        final Configuration configuration = new Configuration(new Version(2, 3, 0));
        configuration.setClassForTemplateLoading(SayMyName.class, "/");

        Spark.get("/", (request, response) -> {

            StringWriter writer = new StringWriter();

            try {
                Template formTemplate = configuration.getTemplate("templates/form.ftl");

                formTemplate.process(null, writer);
            } catch (Exception e) {
                Spark.halt(500);
            }

            return writer;
        });

        Spark.post("/sait", (request, response) -> {
            StringWriter writer = new StringWriter();

            try {
                String name = request.queryParams("name") != null ? request.queryParams("name") : "anonymous";
                String email = request.queryParams("email") != null ? request.queryParams("email") : "unknown";

                Template resultTemplate = configuration.getTemplate("templates/result.ftl");

                Map<String, Object> map = new HashMap<>();
                map.put("name", name);
                map.put("email", email);

                resultTemplate.process(map, writer);
            } catch (Exception e) {
                Spark.halt(500);
            }

            return writer;
        });
    }
}

Now, we only need to run this main class and… that’s all. We can go to our browser and introduce the URL:

http://localhost:4567

We should see our form with our Bootstrap style. If we introduce a username and an email, and we submit the form, we will see in the next page two messages with our form data.

Probably, as you have notice, we have not needed a server and this is because the Spark framework have an embedded Jetty server.

See you.

Advertisements
Spark + Freemarker basic example

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s