Using Thymeleaf in Jakarta EE Servlet

In this tutorial, I show you how to integrate Thymeleaf with Jakarta EE Servlet to replace using JSP in Jakarta EE Servlet applications.

First, I will create a new Jakarta EE Servlet Maven project as an example:

Thymeleaf dependency is as follows:

I will create a new Servlet to handle the request from user:

In the doGet() method of the above IndexServlet, we will use Thymeleaf’s TemplateEngine object to handle the request’s response.

To do this, first, we need to have the TemplateEngine object. But to have the TemplateEngine object, we need the object of the ITemplateResolver interface to configure the location of the template files.

There are many implementations of the ITemplateResolver interface that make it possible to configure the location to template files in different ways:

I will use WebApplicationTemplateResolver for the example of this tutorial:

Now you can instantiate the TemplateEngine object:

You need to register Thymeleaf’s TemplateEngine object with the ServletContext as soon as the application is up and running. We will use the ServletContextListener to do this as follows:

As you can see, we will save this TemplateEngine object to the ServletContext so that every time a request comes to the application, we will retrieve it and handle the response for that request.

Now I will modify the above servlet to get and use the TemplateEngine, as follows:

The process() method of the TemplateEngine object will handle the response for the application. The parameters of this method include the template name, the WebContext object built from the request and response of the current servlet, the Writer object from the response of the current servlet to write the response to the user.

The contents of the home.html file in the src/main/webapp/WEB-INF/templates directory are as follows:

Delete the web.xml file in the src/main/webapp/WEB-INF/ directory (because we are using the @WebServlet annotation) and the index.jsp file in the src/main/webapp/ directory, then run the application, you will see the following result:

One thought on “Using Thymeleaf in Jakarta EE Servlet

Add Comment