logo © 2014

Servlet Quick Start

This quick start explains how to use Jtwig in your Servlet.

1. Dependencies

Depending on the dependency management mechanism used, adding Jtwig dependencies may differ.

To integrate Jtwig one need to add the org.jtwig:jtwig-web:5.85.3.RELEASE dependency. Another important aspect is to add the jcenter repository as Jtwig bundles are stored in bintray.

Gradle

copy
repositories {
    jcenter()
}

dependencies {
    compile "org.jtwig:jtwig-web:5.85.3.RELEASE"
}

Maven

copy

<repositories>
    <repository>
        <id>jcenter</id>
        <url>https://jcenter.bintray.com/</url>
    </repository>
</repositories>

<dependencies>
    <dependency>
        <groupId>org.jtwig</groupId>
        <artifactId>jtwig-web</artifactId>
        <version>5.85.3.RELEASE</version>
    </dependency>
</dependencies>

Download

If you don't make use of dependency management systems, it is also possible to download the dependencies via bintray.

2. Jtwig Template

An example of a Jtwig template placed in the webapp, with path WEB-INF/templates/index.twig.html.

copy
{{ variable }} {{ name }}!

3. Servlet Code

An example of a simple Servlet implementation can be seen below.

copy
package org.jtwig.example;

import com.google.common.collect.ImmutableMap;
import org.jtwig.web.servlet.JtwigRenderer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class HelloWorldServlet extends HttpServlet {
    private final JtwigRenderer renderer = JtwigRenderer.defaultRenderer();

    @Override
    protected void service(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws ServletException, IOException {
        request.setAttribute("variable", "Hello");

        renderer.dispatcherFor("/WEB-INF/templates/index.twig.html")
                .with("name", "Jtwig")
                .render(request, response);
    }
}

All the listed code can be found in Jtwig Examples - Gradle Web Simple.