Issue
First of all, is it possible at all to use Thymeleaf template engine in servlet app? If not, what else template engine can I use instead of JSP?
If it is possible, here is my problem:
I can't access request attribute nor parameter through th:text
. Error: can't resolve 'name_of_attr/param'
.
Now to the details.
I created a very simple servlet app with one servlet and one HTML page.
When I launch the app, my HomeServlet
adds an attribute to the request. Then the servlet using RequestDispatcher
forwards my request to home.html
page. As you can see in the code below, I added ?test=param
to the link, so now we have a parameter too.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setAttribute("test", "test attribute");
req.getRequestDispatcher("/home.html?test=param").forward(req, resp);
}
Now, in home.html
I'm trying to access these attribute and parameter using th:text
.
<body>
<h1>Test</h1>
<div th:text="${test}">...</div>
<div th:text="${param.test}">...</div>
</body>
Nothing works and I get the error mentioned at the top. Maybe I should use some different Thymeleaf tag... Please help me out :)
P.S. I added a thymeleaf dependency to my pom.xml
:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
Also I added the following line to my home.html
page: xmlns:th="http://www.thymeleaf.org"
Solution
Regarding your initial question whether it is possible to use thymeleaf in servlet mechanism, the answer is yes. Please check this example and detailed example which both are good starting points for thymeleaf servlet usage.
As you can see from the examples you should set the variables in WebContext as follows:
package test;
import com.thymeleafexamples.thymeleaf3.config.TemplateEngineUtil;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
@WebServlet("/")
public class IndexServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
TemplateEngine engine = TemplateEngineUtil.getTemplateEngine(request.getServletContext());
WebContext context = new WebContext(request, response, request.getServletContext());
context.setVariable("test", "test attribute");
engine.process("home.html", context, response.getWriter());
}
}
Answered By - Ahmet