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
- org.thymeleaf.context.Context implements IContext
- 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:
WebContext ctx = new WebContext(request, servletContext, request.getLocale());
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.
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.
WebContext ctx = new WebContext(request, servletContext, request.getLocale()); ctx.setVariable("today", dateFormat.format(cal.getTime()));