Context Objects in Thymeleaf

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

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);
	}
}

3. Use Context Variables in Template

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>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>

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.

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.

Speak Your Mind

*