JavaScript, Thymeleaf, Spring MVC and a Dialog Box

We’re going to spend some time Client-Side in v0.2.x of NixMash Spring and will begin with a couple of demonstrations displaying a Bootstrap Dialog Box. We’re going to show:

  1. Populating a dialog box using a Thymeleaf View Fragment
  2. Populating a dialog box with simple JSON from Spring MVC
  3. Requiring the user to be logged-in to view the dialog box with Spring Security

Throughout we’ll see how JavaScript, Thymeleaf and Spring MVC work together to make this really simple. The Dialog Box demos are online at the NixMash Spring Demo Site if you want to see them in action.

Using a Thymeleaf View Fragment

Here’s the “Contact of the Day” Dialog Box populated with a Thymeleaf View Fragment.

It’s not much to write home about, but using a View Fragment makes it very easy to add as much detail and formatting to the dialog box contents as we’d like.

We’re using Nakupanda’s Bootstrap3-Dialog box, by the way. Here’s the link. Looks good, doesn’t it?

The JavaScript that handles the button onclick() function is below. You’ll notice that Thymeleaf creates our JavaScript <script /> block. We do that so we can process Thymeleaf content in the Script Block. We’ll use $.get() to retrieve the View Fragment along with the Contact Model that will populate it. We’re going to pass the populated view to the Bootstrap3-Dialog Box as its message property.

We also see an example of Thymeleaf Inline Expressions with [[#{js.cod.title}]] where we pass a value as the dialog box title.

For completeness here’s the JavaScript which is shared by all of the examples and displays the Bootstrap3 Dialog Box.

Below is the Thymeleaf Fragment that serves as the message property for the Dialog Box. In the second and fourth lines are examples of passing model elements as variables to strings, but otherwise it’s your typical fragment.

Displaying JSON and Restricting Display to Logged-In Users

This section will cover the 2nd and 3rd items on our to-do list where we display a simple JSON message to logged-in users only. Users not logged-in will receive a dialog with a message to log in.

Let’s start by looking at the JavaScript.  Notice how Thymeleaf Inline Expressions work so well with JavaScript. We created a CurrentUser model attribute in a Spring @ControllerAdvice Controller so it’s always available to us. (I blogged about using CurrentUser with Spring Security in this post.) Thymeleaf checks for the existence of that Spring object, and if it exists will display the secret message.

To pass JSON from Spring MVC we’ll create a simple HashMap with the key of “message”. @ResponseBody, along with fasterxml.Jackson configured as our HttpMessageConverter, will take care of the rest.

All of the code discussed in this post is available in NixMash Spring v0.2.1 on GitHub.