Thymeleaf Hello World Example

This tutorial is Hello World example for the template engine framework Thymeleaf. This framework is released few years back and many projects adopted this template engine framework. In simple terms, Thymeleaf is a Java library which can be easily integrated to any Java applications or frameworks like Spring to use as the view templates. Thymeleaf uses XML/XHTML/HTML5 for the transformations.

Basically this framework internally uses the DOM parser for loading the XML structure and create the templates to be displayed to the user. Since it is based on the DOM parsing approach, this framework is suitable only for the web pages to display and not for displaying the large data set. The entire page is loaded as the XML structure in the memory and apply the templates.

Their official website says:

Thymeleaf is a Java library. It is an XML / XHTML / HTML5 template engine (extensible to other formats) that can work both in web and non-web environments. It is better suited for serving XHTML/HTML5 at the view layer of web applications, but it can process any XML file even in offline environments.

One of the main advantage of this framework is that, templates created using this framework is substituted only at the run time, for the prototypes we can use the hard coded values as the alternative. If you develop a prototype, the same files can be used for the dynamic pages since it work in both offline and run time. This is one of the main feature which makes different from other template engines like Velocity and FreeMarker.

If you look at the below code snippet, this will work only in the server. When you invoke outside the server, it will not display any data.

<form:inputText name="userName" value="${user.name}" />

However, look at the Thymeleaf’s syntax below. We can pass the static value to the user while it is accessed in the browser outside the server. When it is accessed run time, the dynamic values are substituted.

<input type="text" name="userName" value="Krishna" th:value="${user.name}" />

This tutorial explains how to setup a very simple Thymeleaf application using Servlet. This can be used with any framework, for the better understanding I have used servlet for creating the templates.

1. Create Thymeleaf Project with Dependencies

If you are using the maven build, please add the following entries to download the required libraries to your local maven repository.

<dependency>
	<groupId>org.thymeleaf</groupId>
	<artifactId>thymeleaf</artifactId>
	<version>2.1.1.RELEASE</version>
</dependency>

If you want to manually download the libraries, the following are the files you need to get it for running this sample application.

  1. thymeleaf-2.1.1.RELEASE.jar
  2. ognl 3.0.6 or later
  3. javassist 3.16.1-GA or later
  4. slf4j 1.6.1 or later

Look at the project structure in Eclipse IDE.

Thymeleaf Projet Structure

2. Create a Servlet

ThymeleafHelloWorldExample.java

package javabeat.net.thymeleaf;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

public class ThymeleafHelloWorldExample extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
    	ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        // XHTML is the default mode, but we will set it anyway for better understanding of code
        templateResolver.setTemplateMode("XHTML");
        templateResolver.setPrefix("/WEB-INF/");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheTTLMs(3600000L);
        TemplateEngine templateEngine = new TemplateEngine();
        templateEngine.setTemplateResolver(templateResolver);
        WebContext ctx = new WebContext(req, resp, getServletConfig().getServletContext(), req.getLocale());
        // This will be prefixed with /WEB-INF/ and suffixed with .html
        templateEngine.process("thymeleaf", ctx, resp.getWriter());
        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 1000);
	}
}

3. Create a Template HTML File

thymeleaf.html

<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Hello World Thymeleaf!!</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p th:text="#{hello}">Hello World Thymeleaf Offline!!</p>
  </body>
</html>

4. Create a Properties File

Note that by default the properties file will be looked for the same name of the template file and in the same directoty.

thymeleaf_en.properties

hello=Hello World Thymeleaf!!

5. Deployment Descriptor

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>Thymeleaf Example</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
	<servlet>
		<servlet-name>thymeleafexample</servlet-name>
		<servlet-class>javabeat.net.ServletExample</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>thymeleafexample</servlet-name>
		<url-pattern>/thymeleafexample</url-pattern>
	</servlet-mapping>

</web-app>

6. Run the Thymeleaf Hello World application

If you access the application using the URL http://localhost:8080/Thymeleaf/thymeleafexample, you would see the following screen.

Thymeleaf Hello World Example

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Comments

  1. how to import this : ThymeleafHelloWorldExample (125) project in eclipse

  2. vinayak k says:

    I want to build thymeleaf hello world example with maven so how we can do tell me the steps?

Speak Your Mind

*