top of page

Using Thymeleaf in Java Web Applications

Thymeleaf is an XML/XHTML/HTML5 template engine and suited for serving XHTML/HTML5 in web applications and it is able to apply a set of transformations to template files (HTML) in order to display dynamic or data and/or text produced by your Java web applications. Thymeleaf is especially suited for working in web applications and it is an elegant, well-formed way of creating templates. Thymeleaf is simple and supports “Natural Templating” and internationalization.


“Natural Templating" means the Thymeleaf template file will open and display normally in a browser, while a JSP file does not, because JSP needs Servlet engine to be executed. Thymeleaf can be integrated with Spring MVC applications.


Thymeleaf’s core library provides "Standard Dialect" which can process templates in web-oriented template modes (XHTML and HTML5 ones).

Thymeleaf - The Natural Templating:


JSP tag libraries could include a fragment of code, which are not directly displayed by a browser like:

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


But, Thymeleaf Standard Dialect allows the fragment of code to be directly displayed by a web browser as well as when the prototype is statically opened in a browser,and that will be substituted by the value resulting from the evaluation of ${user.name} during Thymeleaf processing of the template.


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



Creating and configuring the Template Engine


The doPost(…) method in the servlet contained this sentences...


protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = request.getServletContext(); ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(sc); // XHTML is the default mode, but we will set it anyway for better understanding of code templateResolver.setTemplateMode("XHTML"); templateResolver.setPrefix("/"); templateResolver.setSuffix(".html"); templateResolver.setCacheTTLMs(3600000L); TemplateEngine templateEngine = new TemplateEngine(); templateEngine.setTemplateResolver(templateResolver); WebContext ctx = new WebContext(request, response, getServletConfig().getServletContext(), request.getLocale()); String action =request.getParameter("action"); String forward=null; if(action.equals("persistContact")) { Contact contact = new Contact(); contact.setFirstName(request.getParameter("firstName")); contact.setLastName(request.getParameter("lastName")); contact.setPhone(request.getParameter("phone")); contact.setEmail(request.getParameter("email")); contact.setAddress(request.getParameter("address")); contact.setQuery(request.getParameter("query")); contactRepository = new ContactRepositoryImpl(); contactRepository.persistContactDetails(contact); request.setAttribute("contact", contact); forward = "contactConfirm"; templateEngine.process(forward, ctx, response.getWriter()); response.setContentType("text/html;charset=UTF-8"); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 1000); }


The Template Resolver

Let’s start with the Template Resolver:


ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(req.getServletContext());


Template Resolvers are objects that implement an interface from the Thymeleaf API called org.thymeleaf.templateresolver.ITemplateResolver:


These objects are in charge of determining how our templates will be accessed, and in this GTVG application, the org.thymeleaf.templateresolver.ServletContextTemplateResolver implementation that we are using specifies that we are going to retrieve our template files as resources from the Servlet Context: an application-wide javax.servlet.ServletContext object that exists in every Java web application.


But that’s not all we can say about the template resolver, because we can set some configuration parameters on it. First, the template mode, one of the standard ones:


templateResolver.setTemplateMode("XHTML");

XHTML is the default template mode for ServletContextTemplateResolver, but it is good practice to establish it anyway so that our code documents clearly what is going on.


templateResolver.setPrefix("/WEB-INF/templates/");

templateResolver.setSuffix(".html");

These prefix and suffix do exactly what it looks like: modify the template names that we will be passing to the engine for obtaining the real resource names to be used.

Optionally, the amount of time that a parsed template living in cache will be considered valid can be configured at the Template Resolver by means of the cacheTTLMs property:

templateResolver.setCacheTTLMs(3600000L);


public class ServletContextTemplateResolver extends AbstractConfigurableTemplateResolver

Implementation of ITemplateResolver that extends AbstractConfigurableTemplateResolver and creates ServletContextTemplateResource instances for template resources.

Note a class with this name existed since 1.0, but it was completely rewritten in Thymeleaf 3.0



The Template Engine

TemplateEngine templateEngine = new TemplateEngine();

Template Engine objects are of class org.thymeleaf.TemplateEngine, and these are the lines that created our engine in the current example:

templateEngine = new TemplateEngine();

templateEngine.setTemplateResolver(templateResolver);

Rather simple, isn’t it? All we need is to create an instance and set the Template Resolver to it.

A template resolver is the only required parameter a TemplateEngine needs, although of course there are many others that will be covered later (message resolvers, cache sizes, etc). For now, this is all we need.

Our Template Engine is now ready and we can start creating our pages using Thymeleaf.

org.thymeleaf.TemplateEngine

public class TemplateEngine extends Object implements ITemplateEngine

Main class for the execution of templates. This is the only implementation of ITemplateEngine provided out of the box by Thymeleaf.

Which means that our Servlet class is in charge of creating and configuring one of the most important objects in a Thymeleaf-enabled application: The TemplateEngine instance.

Configuring the TemplateEngine

Once created, an instance of TemplateEngine has to be typically configured a mechanism for resolving templates (i.e. obtaining and reading them):

  • One or more Template Resolvers (implementations of ITemplateResolver), in charge of reading or obtaining the templates so that the engine is able to process them. If only one template resolver is set (the most common case), the setTemplateResolver(ITemplateResolver) method can be used for this.





Featured Posts
Check back soon
Once posts are published, you’ll see them here.
Follow Us
  • Facebook Basic Square
  • Twitter Basic Square
  • Google+ Basic Square
Recent Posts
Archive
Search By Tags
No tags yet.
bottom of page