JavaBeat

  • Home
  • Java
    • Java 7
    • Java 8
    • Java EE
    • Servlets
  • Spring Framework
    • Spring Tutorials
    • Spring 4 Tutorials
    • Spring Boot
  • JSF Tutorials
  • Most Popular
    • Binary Search Tree Traversal
    • Spring Batch Tutorial
    • AngularJS + Spring MVC
    • Spring Data JPA Tutorial
    • Packaging and Deploying Node.js
  • About Us
    • Join Us (JBC)
  • Privacy

Thymeleaf Tutorials

March 3, 2014 by Krishna Srinivasan Leave a Comment

What is Thymeleaf?

Thymeleaf is Java library and template engine that supports XML/XHTML/HTML5 template engines. It is very well suited for processing the XHTML and HTML5 documents in the web applications. Also it can process the XML documents while work as offline applications. This is a new template engine and adopted by many of the projects which are looking for the alternative to JSP. It has separate module for Spring MVC integration. This helps the spring developers to use thymeleaf out of the box from their spring applications.

The latest version of this template engine is 2.1. As rightly said, this template engine is evolving and we could see lot of optional modules for integrating to the other frameworks. This post publishes the collection of tutorials on thymeleaf in JavaBeat.

Thymeleaf Template Engine Tutorials

Thymeleaf Tutorials

  • 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.
  • WebContext in Thymeleaf : If you look at the example, it uses some kind of context to transfer the variables across its application. The same way how ServletContext or SpringApplicationContext works, Thymeleaf has its own context framework to maintain its context across the applications and retain the values throughout the application scope. This tutorial explains the various types of context available and default values stored with the thymeleaf’s context environment.
  • Expression Language in Thymeleaf : When we work with web frameworks, one of the important feature is the simplification of using the expression languages. This tutorial explains the various syntax used by the Thymeleaf framework for accessing the values using its expression syntax. Look at the below list of various types of expression syntax supported by this framework.
  • Context Objects in Thymeleaf : Thymeleaf have number of default objects in the context which are more than just the basics objects like session, request, etc., there are many other utility objects can be accessed in the context. This tutorial explains the default context objects used in the Thymeleaf framework.
  • org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression : When you work with Thymeleaf application, you would have encountered the TemplateProcessingException exceptions. The problem is the use of default context variables.
  • How To Set Attributes in Thymeleaf Template using th:attr? : This tutorial explains how to set the attribute to the template at the time of processing. This feature is very useful for creating the templates. Thymeleaf provides very easy syntax for just adding the attributes dynamically from the properties files or context variables.
  • How To Use th:each For Iteration In Thymeleaf Template? : This tutorial explains how to iterate the list of values from an object. For Iteration In Thymeleaf Template, it provides th:each attribue for using inside a table element to iterate over the list of objects and display the list. This feature also provides iterationStatus context to retrieve the extra details about size of the list, row count, whether that is the first or last element, etc. This feature is very useful for creating the table list with the dynamic values.
  • How To Use Switch Statement (th:switch) In Thymeleaf Template? : This tutorial explains how to use the switch statements inside Thymeleaf template. Thymeleaf provides th:switch attribute for using switch functionality. This feature is extension of my previous example on iteration in thymeleaf template.

Reference

  • Official website

Filed Under: Tutorials Tagged With: Thymeleaf

How To Use Switch Statement (th:switch) In Thymeleaf Template?

November 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to use the switch statements inside Thymeleaf template. Thymeleaf provides th:switch attribute for using switch functionality. This feature is extension of my previous example on iteration in thymeleaf template.

1. Set Up Thymeleaf Application

To demonstrate this example, I am using our previous hello world example.Use the same example and replace our code snippet as below. You can use the set up details as mentioned in the hello world example.

2. Create Template with th:switch

If you look at the below example, the tamplate has the th:switch which is replaced with the dynamic values by the template engine.

employees.xml

[code lang=”xml”]
<!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>Iteration in Thymeleaf Template Engine!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Employees</h1>
<table>
<tr>
<th>SNO</th>
<th>ID</th>
<th>NAME</th>
<th>CITY</th>
<th>COUNTRY</th>
<th>ROLE</th>
</tr>
<tr th:each="emp,iterationStatus : ${employees}">
<td th:text="${iterationStatus.count}">1</td>
<td th:text="${emp.id}">001</td>
<td th:text="${emp.name}">Name</td>
<td th:text="${emp.city}">City</td>
<td th:text="${emp.country}">Country</td>
<td>
<div th:switch="${emp.role}">
<p th:case="’Admin’">User is an Administrator</p>
<p th:case="’Manager’">User is a Manager</p>
<p th:case="’Engineer’">User is an Engineer</p>
</div>
</td>
</tr>
</table>
</body>
</html>

[/code]

3. Create Bean Employee

Employee.java

[code lang=”java”]
package javabeat.net.thymeleaf;

public class Employee {
private String id;
private String name;
private String role;
private String city;
private String country;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

[/code]

4. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafSwitchExample.java

[code lang=”java”]
package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

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 ThymeleafSwitchExample 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());
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee employee = new Employee();
employee.setId("001");
employee.setName("Rahul");
employee.setRole("Manager");
employee.setCity("Bangalore");
employee.setCountry("India");
employees.add(employee);
employee = new Employee();
employee.setId("002");
employee.setName("Deepan");
employee.setRole("Admin");
employee.setCity("Namakkal");
employee.setCountry("India");
employees.add(employee);
employee = new Employee();
employee.setId("003");
employee.setName("Ashwanth");
employee.setRole("Engineer");
employee.setCity("Bangalore");
employee.setCountry("India");
employees.add(employee);

// This will be prefixed with /WEB-INF/ and suffixed with .html
ctx.setVariable("employees", employees);
templateEngine.process("employees", 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);
}
}
[/code]

5. Run The Thymeleaf Application

If you execute the above code, you would see the below output as below.

switch-thymeleaf

Filed Under: Web Frameworks Tagged With: switch, template engine, Thymeleaf

How To Use th:each For Iteration In Thymeleaf Template?

November 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to iterate the list of values from an object. For Iteration In Thymeleaf Template, it provides th:each attribue for using inside a table element to iterate over the list of objects and display the list. This feature also provides iterationStatus context to retrieve the extra details about size of the list, row count, whether that is the first or last element, etc. This feature is very useful for creating the table list with the dynamic values.

1. Set Up Thymeleaf Application

To demonstrate this example, I am using our previous hello world example.Use the same example and replace our code snippet as below. You can use the set up details as mentioned in the hello world example.

2. Create Template with th:each

If you look at the below example, the tamplate has the th:each which is replaced with the dynamic values by the template engine.

employees.xml

[code lang=”xml”]
<!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>Iteration in Thymeleaf Template Engine!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1>Employees</h1>
<table>
<tr>
<th>SNO</th>
<th>ID</th>
<th>NAME</th>
<th>CITY</th>
<th>COUNTRY</th>
</tr>
<tr th:each="emp,iterationStatus : ${employees}">
<td th:text="${iterationStatus.count}">1</td>
<td th:text="${emp.id}">001</td>
<td th:text="${emp.name}">Name</td>
<td th:text="${emp.city}">City</td>
<td th:text="${emp.country}">Country</td>
</tr>
</table>
</body>
</html>

</body>
</html>

[/code]

3. Create Bean Employee

Employee.java

[code lang=”java”]
package javabeat.net.thymeleaf;

public class Employee {
private String id;
private String name;
private String city;
private String country;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
[/code]

4. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafIterationExample.java

[code lang=”java”]
package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

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 ThymeleafIterationExample 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());
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee employee = new Employee();
employee.setId("001");
employee.setName("Rahul");
employee.setCity("Bangalore");
employee.setCountry("India");
employees.add(employee);
employee = new Employee();
employee.setId("002");
employee.setName("Deepan");
employee.setCity("Namakkal");
employee.setCountry("India");
employees.add(employee);
employee = new Employee();
employee.setId("003");
employee.setName("Ashwanth");
employee.setCity("Bangalore");
employee.setCountry("India");
employees.add(employee);

// This will be prefixed with /WEB-INF/ and suffixed with .html
ctx.setVariable("employees", employees);
templateEngine.process("employees", 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);
}
}

[/code]

5. Run The Thymeleaf Application

If you execute the above code, you would see the below output as below.

iteration-thymeleaf

Filed Under: Web Frameworks Tagged With: template engine, Thymeleaf

How To Set Attributes in Thymeleaf Template using th:attr?

November 27, 2013 by Krishna Srinivasan Leave a Comment

In my previous articles I have explained about the hello world example and the expression language. This tutorial explains how to set the attribute to the template at the time of processing. This feature is very useful for creating the templates. Thymeleaf provides very easy syntax for just adding the attributes dynamically from the properties files or context variables.

1. Set Up Thymeleaf Application

To demonstrate using the attribute values, I am using our previous hello world example.Use the same example and replace our code snippet below.

2. Create Template with th:attr

If you look at the below example, the tamplate has the th:attr which is replaced with the dynamic values by the template engine. Note that there are number of attributes and many other features are supported for setting the attribute values. Here I am explaining with a very simple example.

attributes.html

[code lang=”xml”]
<!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>How to set Attribute Values!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p><b>Use th:attr</b></p>
<fieldset>
<input type="text" name="email" th:attr="class=#{input.class}"/>
<input type="submit" value="Subscribe me!" th:attr="value=#{input.submit}"/>
</fieldset>
<a href="register.html" th:attr="href=@{/LoginRegister.html}">Register Here</a>
<p><b>Use Specific Attributes</b></p>
<fieldset>
<input type="text" name="email" th:class="#{input.class}"/>
<input type="submit" value="Subscribe me!" th:value="#{input.submit}"/>
</fieldset>
<a href="register.html" th:href="@{/LoginRegister.html}">Register Here</a>
<p><b>Append Using th:attrappend</b></p>
<fieldset>
<input type="text" name="email" class="input" th:attrappend="class=’ ‘ + #{input.class}"/>
<input type="submit" value="Subscribe me!" th:attr="value=#{input.submit}"/>
</fieldset>
<a href="register.html" th:attr="href=@{/LoginRegister.html}">Register Here</a>

</body>
</html>

[/code]

3. Create Servlet with Thymeleaf Context and Attach Template

ThymeleafSetAttributeExample.java

[code lang=”java”]
package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

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 ThymeleafSetAttributeExample 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("attribute", 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);
}
}

[/code]

4. Create Property File

attributes_en.properties/strong>

[code]
input.class=inputstyle
input.submit=Form Submit
input.href=LoginRegister.html
[/code]

5. Run The Thymeleaf Application

If you execute the above code, you would see the below screen.

set-attribute-thymeleaf

If you look at the view source, the above template converted as below.

[code lang=”xml”]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to set Attribute Values!!</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<p><b>Use th:attr</b></p>
<fieldset>
<input type="text" name="email" class="inputstyle" />
<input type="submit" value="Form Submit" />
</fieldset>
<a href="/Thymeleaf/LoginRegister.html" shape="rect">Register Here</a>
<p><b>Use Specific Attributes</b></p>
<fieldset>
<input type="text" name="email" class="inputstyle" />
<input type="submit" value="Form Submit" />
</fieldset>
<a href="/Thymeleaf/LoginRegister.html" shape="rect">Register Here</a>
<p><b>Append Using th:attrappend</b></p>
<fieldset>
<input type="text" name="email" class="input inputstyle" />
<input type="submit" value="Form Submit" />
</fieldset>
<a href="/Thymeleaf/LoginRegister.html" shape="rect">Register Here</a>

</body>
</html>
[/code]

Filed Under: Web Frameworks Tagged With: template engine, Thymeleaf

org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression

November 26, 2013 by Krishna Srinivasan Leave a Comment

When you work with Thymeleaf application, you would have encountered the TemplateProcessingException exceptions. The problem is the use of default context variables. It could be because of

  1. Wrong use of the context variable name (or)
  2. The property name accessed by the context variable object is not correct.

[code]
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating OGNL expression: "#httpSession.sessionValue" (thymeleaf:11)
at org.thymeleaf.standard.expression.OgnlVariableExpressionEvaluator.evaluate(OgnlVariableExpressionEvaluator.java:126)
at org.thymeleaf.standard.expression.VariableExpression.executeVariable(VariableExpression.java:149)
at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:59)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:103)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:133)
at org.thymeleaf.standard.expression.Expression.execute(Expression.java:120)
at org.thymeleaf.standard.processor.attr.AbstractStandardTextChildModifierAttrProcessor.getText(AbstractStandardTextChildModifierAttrProcessor.java:68)
at org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor.getModifiedChildren(AbstractTextChildModifierAttrProcessor.java:59)
at org.thymeleaf.processor.attr.AbstractChildrenModifierAttrProcessor.processAttribute(AbstractChildrenModifierAttrProcessor.java:58)
at org.thymeleaf.processor.attr.AbstractAttrProcessor.doProcess(AbstractAttrProcessor.java:87)
at org.thymeleaf.processor.AbstractProcessor.process(AbstractProcessor.java:212)
at org.thymeleaf.dom.Node.applyNextProcessor(Node.java:973)
at org.thymeleaf.dom.Node.processNode(Node.java:928)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
at org.thymeleaf.dom.Node.processNode(Node.java:947)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
at org.thymeleaf.dom.Node.processNode(Node.java:947)
at org.thymeleaf.dom.NestableNode.computeNextChild(NestableNode.java:672)
at org.thymeleaf.dom.NestableNode.doAdditionalProcess(NestableNode.java:655)
Caused by: ognl.NoSuchPropertyException: org.apache.catalina.session.StandardSessionFacade.sessionValue
at ognl.ObjectPropertyAccessor.getProperty(ObjectPropertyAccessor.java:151)
at ognl.OgnlRuntime.getProperty(OgnlRuntime.java:2334)
at ognl.ASTProperty.getValueBody(ASTProperty.java:114)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.ASTChain.getValueBody(ASTChain.java:141)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
at ognl.SimpleNode.getValue(SimpleNode.java:258)
at ognl.Ognl.getValue(Ognl.java:494)
at ognl.Ognl.getValue(Ognl.java:458)
at org.thymeleaf.standard.expression.OgnlVariableExpressionEvaluator.evaluate(OgnlVariableExpressionEvaluator.java:114)
[/code]

Filed Under: Web Frameworks Tagged With: Exceptions, Thymeleaf

Context Objects in Thymeleaf

November 26, 2013 by Krishna Srinivasan Leave a Comment

In my previous article I have explained about the different types of expression languages used in Thymeleaf framework. If you have worked with JSP or any other web frameworks, there are number of implicit objects available in the context for the free use. These objects are created by the container and made it available with default context for helping the developer to easily access and use it in the code. Thymeleaf also have number of default objects in the context which are more than just the basics objects like session, request, etc., there are many other utility objects can be accessed in the context. This tutorial explains the default context objects used in the Thymeleaf framework.

From the Thymeleaf Reference Docs:

Expression Basic Objects

  • #ctx: the context object.
  • #vars: the context variables.
  • #locale: the context locale.
  • #httpServletRequest: (only in Web Contexts) the HttpServletRequest object.
  • #httpSession: (only in Web Contexts) the HttpSession object.

Expression Utility Objects

  • #dates: utility methods for java.util.Date objects: formatting, component extraction, etc.
  • #calendars: analogous to #dates, but for java.util.Calendar objects.
  • #numbers: utility methods for formatting numeric objects.
  • #strings: utility methods for String objects: contains, startsWith, prepending/appending, etc.
  • #objects: utility methods for objects in general.
  • #bools: utility methods for boolean evaluation.
  • #arrays: utility methods for arrays.
  • #lists: utility methods for lists.
  • #sets: utility methods for sets.
  • #maps: utility methods for maps.
  • #aggregates: utility methods for creating aggregates on arrays or collections.
  • #messages: utility methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
  • #ids: utility methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).

1. Set Up Thymeleaf Application

To demonstrate using the context variables, I am using our previous hello world example.Use the same example and replace our code snippet below.

2. Add Context Variables

ThymeleafHelloWorldExample.java

[code lang=”java”]package javabeat.net.thymeleaf;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.TreeSet;

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());
ctx.setVariable("today", Calendar.getInstance());
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("Value Sample 1");
arrayList.add("Value Sample 2");

TreeSet<String> set = new TreeSet<String>();
set.add("Set Sample 1");
set.add("Set Sample 2");
set.add("Set Sample 3");

ctx.setVariable("contextValue", "Store Context Value");
ctx.setVariable("listExample", arrayList);
ctx.setVariable("setExample", set);

req.getSession().setAttribute("sessionValue", "Store Session Value");

// 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);
}
}[/code]

3. Use Context Variables in Template

thymeleaf.html

[code lang=”xml”]<!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>Session value: <span th:text="${session.sessionValue}">No Value</span></p>
<p>Locale country:<span th:text="${#locale.country}">US</span></p>
<p>Today is: <span th:text="${#calendars.format(today,’dd MMMM yyyy’)}">Empty</span></p>
<p>Is Empty String: <span th:text="${#strings.isEmpty(contextValue)}">True</span></p>
<p>Upper Case String: <span th:text="${#strings.toUpperCase(‘javabeat’)} ">None</span></p>
<p>List Size: <span th:text="${#lists.size(listExample)}">0</span></p>
<p>Set Size: <span th:text="${#sets.size(setExample)}">0</span></p>
<p>Format Number: <span th:text="${#numbers.formatInteger(100000,3,’POINT’)}">0</span></p>
</body>
</html>[/code]

4. Run the Application

If you run the above application, you would get the following output.

Thymeleaf Context Object

Please refer here for the complete list of variables and properties.

Filed Under: Web Frameworks Tagged With: context object, Thymeleaf

Expression Language in Thymeleaf

November 26, 2013 by Krishna Srinivasan Leave a Comment

In my previous tutorial I have explained about the simple hello world example to start writing your first example using the Thymeleaf framework. If you are not familiar with this new framework, I would recommend to read that tutorial before start reading this tutorial. When we work with web frameworks, one of the important feature is the simplification of using the expression languages. This tutorial explains the various syntax used by the Thymeleaf framework for accessing the values using its expression syntax. Look at the below list of various types of expression syntax supported by this framework.

  • Simple expressions
    • Variable Expressions: ${…}
    • Selection Variable Expressions: *{…}
    • Message Expressions: #{…}
    • Link URL Expressions: @{…}
  • Literals
    • Text literals: ‘one text’, ‘Another one!’,…
    • Number literals: 0, 34, 3.0, 12.3,…
    • Boolean literals: true, false
    • Null literal: null
    • Literal tokens: one, sometext, main,…
  • Text operations
    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  • Arithmetic operations
    • Binary operators: +, -, *, /, %
    • Minus sign (unary operator): –
  • Boolean operations
    • Binary operators: and, or
    • Boolean negation (unary operator): !, not
  • Comparisons and equality
    • Comparators: >, <, >=, <= (gt, lt, ge, le)
    • Equality operators: ==, != (eq, ne)
  • Conditional operators
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)

Among the above list, first one is the important to understand.

  • Expression Language in JSP 2.0
  • Spring Expression Language

1. Variable Expression

Variable Expressions and Selection Variable Expressions work similar except that later will work different when used with seletecd objects. Look at the below example.

[code lang=”xml”]
<div th:object="${obj.userObj}">
<p>Name: <span th:text="*{firstName}">Krishna</span>.</p>
<p>Surname: <span th:text="*{lastName}">Srinivasan</span>.</p>
<p>Nationality: <span th:text="*{country}">India</span>.</p>
</div>
[/code]

Which is equivalent to

[code lang=”xml”]
<div>
<p>Name: <span th:text="*{obj.userObj.firstName}">Krishna</span>.</p>
<p>Surname: <span th:text="*{obj.userObj.lastName}">Srinivasan</span>.</p>
<p>Nationality: <span th:text="*{obj.userObj.country}">India</span>.</p>
</div>
[/code]

We can use dollar and asterisk syntax together. From the above example, you could notice that instead of asterisk, you can even use the dollar syntax.

2. Message Expression

It is very simple to access a message from a resource bundles.

[code]
<p th:text="#{hello}">Hello World Thymeleaf Offline!!</p>
[/code]

The above “hello” key is taken from message properties file. Also you can use the dynamic values in the messages.

[code]
hello=Welcome {0}, Hello World Thymeleaf!!
[/code]

For the above property configuration, you can pass the parameter as below

[code]
<p th:text="#{hello(${userObj.userName})}}">Hello World Thymeleaf Offline!!</p>
[/code]

3. Link Expressions

Thymeleaf Standard Dialect has a special syntax for the links, the @ syntax: @{…}. Thymeleaf can handle absolute URLs like http://www.thymeleaf.org can handle at any situation. But for the relative URLs, we have specify the context path. th:href is used for setting the href attribute of the link element. Look at the example snippet below.

Absolute URL

[code]
<a href="user.html" th:href="@{http://localhost:8080/user/details(userId=${o.id})}">View User</a>
[/code]

Relative URL

In the case of absolute URL, context path is added to the final URL.

[code]
<a href="user.html" th:href="@{/user/details(userId=${o.id})}">View User</a>
[/code]

I hope this article provided basic idea of how to use the expression language in Thymeleaf. Other types of expressions are not new and easy to use, so I am not explaining in this tutorial. If you have any clarification, please write it in the comments section.

Filed Under: Web Frameworks Tagged With: expression language, Thymeleaf

WebContext in Thymeleaf

November 22, 2013 by Krishna Srinivasan Leave a Comment

In my previous tutorial I have explained about writing your first Hello World example using Thymeleaf template engine framework. If you look at the example, it uses some kind of context to transfer the variables across its application. The same way how ServletContext or SpringApplicationContext works, Thymeleaf has its own context framework to maintain its context across the applications and retain the values throughout the application scope. This tutorial explains the various types of context available and default values stored with the thymeleaf’s context environment.

There are two context available with this template engine

  1. org.thymeleaf.context.Context implements IContext
  2. org.thymeleaf.context.WebContext implements IWebContext

The second one WebContext is our preferred contact object to use in our application. This context is specific to Web Applications. This itself extending the IContext. We are not directly using the IContext in our web applications, it contains very common behavior of the context mechanism, this may be used in the future releases when introducing some more sub context apart from the WebContext.

You can create a WebContext like this:

[code lang=”java”]
WebContext ctx = new WebContext(request, servletContext, request.getLocale());
[/code]

When the context is created, it creates a object which holds the two values for the template engine. The object name is execInfo. The two variables are templateName and now. these can be accessed across anywhere in the templates.

[code]
${execInfo.templateName}
${execInfo.now}
[/code]

As told, this context object used for transferring the values to template engine. You can set the values to context object as you do with normal JSP or Servlet.

[code lang=”java”]
WebContext ctx = new WebContext(request, servletContext, request.getLocale());
ctx.setVariable("today", dateFormat.format(cal.getTime()));
[/code]

Filed Under: Web Frameworks Tagged With: Thymeleaf

Thymeleaf Hello World Example

November 22, 2013 by Krishna Srinivasan Leave a Comment

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.

[code lang=”xml”]
<form:inputText name="userName" value="${user.name}" />
[/code]

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.

[code lang=”xml”]
<input type="text" name="userName" value="Krishna" th:value="${user.name}" />
[/code]

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.

[code lang=”xml”]
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
[/code]

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

[code lang=”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);
}
}
[/code]

3. Create a Template HTML File

thymeleaf.html

[code lang=”xml”]
<!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>
[/code]

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

[code]
hello=Hello World Thymeleaf!!
[/code]

5. Deployment Descriptor

web.xml

[code lang=”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>
[/code]

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

  • Download Source Code : [download id=”21″]

Filed Under: Web Frameworks Tagged With: Thymeleaf

Follow Us

  • Facebook
  • Pinterest

As a participant in the Amazon Services LLC Associates Program, this site may earn from qualifying purchases. We may also earn commissions on purchases from other retail websites.

JavaBeat

FEATURED TUTORIALS

Answered: Using Java to Convert Int to String

What is new in Java 6.0 Collections API?

The Java 6.0 Compiler API

Copyright © by JavaBeat · All rights reserved