Home » Java » Enterprise Java » Spring MVC and Thymeleaf: how to acess data from templates

About Rafal Borowiec

Rafal is an IT specialist with about 8 years of commercial experience, specializing in software testing and quality assurance, software development, project management and team leadership. He is currently holding a position of a Team Leader at Goyello where he is mainly responsible for building and managing teams of professional developers and testers. He is also responsible for maintaining relations with customers and acquiring new ones, mainly through consultancy. He believes in Agile project management and he is a big fan of technology, especially Java related (but not limited too). He likes sharing knowledge about software development and practices, through his blog (blog.codeleak.pl) and Twitter (@kolorobot) but also on internal and external events like conferences or workshops.

Spring MVC and Thymeleaf: how to acess data from templates

In a typical Spring MVC application, @Controller classes are responsible for preparing a model map with data and selecting a view to be rendered. This model map allows for the complete abstraction of the view technology and, in the case of Thymeleaf, it is transformed into a Thymeleaf VariablesMap object that makes all the defined variables available to expressions executed in templates.

Spring model attributes

Spring MVC calls the pieces of data that can be accessed during the execution of views model attributes. The equivalent term in Thymeleaf language is context variables. There are several ways of adding model attributes to a view in Spring MVC. Below you will find some common cases: Add attribute to Model via its `addAttribute` method:

@RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
        model.addAttribute("messages", messageRepository.findAll());
        return "message/list";

Return `ModelAndView` with model attributes included:

@RequestMapping(value = "message", method = RequestMethod.GET)
public ModelAndView messages() {
        ModelAndView mav = new ModelAndView("message/list");
        mav.addObject("messages", messageRepository.findAll());
        return mav;

Expose common attributes via methods annotated with `@ModelAttribute`:

public List<Message> messages() {
        return messageRepository.findAll();

As you may have noticed, in all the above cases the `messages` attribute is added to the model and it will be available in Thymeleaf views.

In Thymeleaf, these model attributes can be accessed with the following syntax: `${attributeName}` which is a Spring EL expression.

You can access model attributes in views with Thymeleaf as follows:

 <tr th:each="message : ${messages}">
        <td th:text="${message.id}">1</td>
        <td><a href="#" th:text="${message.title}">Title ...</a></td>
        <td th:text="${message.text}">Text ...</td>

Request parameters

Request parameters can be easily accessed in Thymeleaf views. Request parameters are passed from the client to server like:


Let’s assume we have a `@Controller` that sends a redirect with a request parameter:

    public class SomeController {
        public String redirect() {
            return "redirect:/query?q=Thymeleaf Is Great!";

In order to access the `q` parameter you can use the `param.` prefix:

<p th:text="${param.q[0]}" th:unless="${param.q == null}">Test</p>

Two things are important to notice in the above example:

  • `${param.q != null}` checks if the parameter `q` is set
  • Parameters are always string arrays, as they can be multivalued (e.g. `https://example.com/query?q=Thymeleaf%20Is%20Great!&q=Really%3F)

Another way to access request parameters is by using the special object `#httpServletRequest` that gives you direct access to the `javax.servlet.http.HttpServletRequest` object:

<p th:text="${#httpServletRequest.getParameter('q')}" th:unless="${#httpServletRequest.getParameter('q') == null}">Test</p>

Session attributes

In the below example we add `mySessionAttribute` to session:

String index(HttpSession session) {
        session.setAttribute("mySessionAttribute", "someValue");
        return "index";

Similarly to the request parameters, session attributes can be access by using the `session.` prefix:

 <div th:text="${session.mySessionAttribute}">[...]</div>

Or by using `#httpSession`, that gives you direct access to the `javax.servlet.http.HttpSession` object.

ServletContext attributes, Spring beans

The full version of this article, that I wrote for thymeleaf.org, with a great help of Daniel Fernández, can be found here: http://www.thymeleaf.org/springmvcaccessdata.html

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

Leave a Reply

Your email address will not be published. Required fields are marked *


− 1 = zero

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Do you want to know how to develop your skillset and become a ...

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.