Home  >  Thymeleaf

Java Thymeleaf Example | Getting Started with Thymeleaf

By Arvind Rai, October 26, 2015
On this page we will provide Java Thymeleaf example. It is a template engine which can process XML, XHTML, HTML5. Thymeleaf processes templates fast with least amount of IO operations. Thymeleaf gives speed to project development by way that front end and backend team can work together on UI pages. Thymeleaf provides internalization. The basic API provided by Thymeleaf are ServletContextTemplateResolver and TemplateEngine. ServletContextTemplateResolver resolves templates from location and TemplateEngine processes the templates using TemplateEngine.process() method. The expression in template gets values from property file and WebContext. We must care that property file and template must be of same name and located in same directory.

Software used in Demo

1. Java 8
2. Thymeleaf 3.0.0.ALPHA03
3. Servlet 3.1
4. Tomcat 8
5. Gradle
6. Eclipse


Project Structure in Eclipse

Java Thymeleaf Example | Getting Started with Thymeleaf

Gradle


build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'war'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'javax.servlet:javax.servlet-api:3.1.0'
    compile 'org.thymeleaf:thymeleaf:3.0.0.ALPHA03'
}  

Using th:text and externalizing text

Find the HTML page used in our demo. If we directly access this HTML page, we will see offline values and when we run via server, we get values of tag body processed by Thymeleaf.
WEB-INF\templates\welcome.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>Thymeleaf Demo</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p th:text="#{welcome.msg}">Welcome Offline</p>
    <p>Date : <span th:text="${currentDate}">Sat Oct 24 2015</span></p>
  </body>
</html> 

th:text: Attribute to evaluate expression and sets the result to body of tag.
#{...}: Fetches the value from property file. The expression #{welcome.msg} gets the value of key welcome.msg from property file.
${...}: This is OGNL expression and fetches the value set in org.thymeleaf.context.WebContext. The expression ${currentDate} gets the value for the attribute currentDate set in WebContext.

Resolve Templates using ServletContextTemplateResolver and process it using TemplateEngine.process()


ThymeleafAppUtil.java
package com.concretepage;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
public class ThymeleafAppUtil {
     private static TemplateEngine templateEngine;
     static {
         ServletContextTemplateResolver templateResolver = 
                 new ServletContextTemplateResolver();
         templateResolver.setTemplateMode("XHTML");
         templateResolver.setPrefix("/WEB-INF/templates/");
         templateResolver.setSuffix(".html");
         templateResolver.setCacheTTLMs(3600000L);
         templateEngine = new TemplateEngine();
         templateEngine.setTemplateResolver(templateResolver);
     }
     public static TemplateEngine getTemplateEngine() {
	 return templateEngine;
     }
} 

ServletContextTemplateResolver: It resolves the Thymeleaf templates. We need to set template mode, suffix, prefix etc.
TemplateEngine: It executes Thymeleaf templates.

Property file used in demo

Property file and template must have same name and located in same directory.
WEB-INF\templates\welcome_en.properties
welcome.msg= Welcome to Thymeleaf World!
 

Run Demo with Servlet


WelcomeServlet.java
package com.concretepage;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/welcome", loadOnStartup = 1)
public class WelcomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
	        doGet(request,response);
	}
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/html;charset=UTF-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		WelcomeApplication application = new WelcomeApplication();
		application.process(request, response);
	}
} 

Output

Find the URL to run the demo.
http://localhost:8080/concretepage-1/welcome
Java Thymeleaf Example | Getting Started with Thymeleaf

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us