1. Overview

In this tutorial, we're going to show how to access Spring MVC objects in Thymeleaf views that contain JavaScript code. We'll use Spring Boot and the Thymeleaf template engine in our examples, but the idea works for other template engines as well.

We're going to describe two cases: when JavaScript code is embedded or internal to the web page generated by the engine, and when it is external to the page – for example, in a separate JavaScript file.

2. Setup

Let's assume that we've already configured a Spring Boot web application that uses Thymeleaf template engine. Otherwise, you might find these tutorials useful to start:

Furthermore, let's suppose that our application has a controller corresponding to an endpoint /index that renders a view from a template named index.html. This template might include an embedded or an external JavaScript code, say script.js.

Our goal is to be able to access Spring MVC parameters from either embedded or external JavaScript (JS) code.

3. Access the Parameters

First of all, we need to create the model variables that we want to use from the JS code.

In Spring MVC, there are various ways of doing this. Let's use the ModelAndView approach:

@RequestMapping("/index")
public ModelAndView thymeleafView(Map<String, Object> model) {
    model.put("number", 1234);
    model.put("message", "Hello from Spring MVC");
    return new ModelAndView("thymeleaf/index");
}

We can find other possibilities in our tutorial on Model, ModelMap, and ModelView in Spring MVC.

4. Embedded JS Code

Embedded JS code is nothing but a part of the index.html file that is located inside the