Finally announcing my next course. The intro price of the upcoming “Learn Spring” course will permanently increase by $50 at end-of-day today:

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.

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:

Thymeleaf template engine replaces every expression by a value that is available in the scope of the current execution. This means that the template engine transforms the code mentioned above into the following HTML code:

With this wrapper, we can guarantee that the JS code is executed only when the whole page content, and hence all other embedded JS code, is completely loaded.

6. A Bit of Explanation

In Spring MVC, the Thymeleaf template engine parses only the template file (index.html in our case) and converts it into an HTML file. This file, in its turn, might include references to other resources that are out of the scope of the template engine. It’s the user’s browser that parses those resources and renders the HTML view.

Therefore, those resources are not parsed by the template engine, and we may inject variables defined in the controller only into the embedded JS code that then becomes available for the external JS code.

7. Conclusion

In this tutorial, we’ve learned how to access Spring MVC parameters inside a JavaScript code.