Fadeout Feedback Messages in Spring MVC

Contact Entry and Update forms have been added in NixMash Spring v0.1.5, so we need proper feedback messages like the one shown below.

With Bootstrap we can nicely format the feedback message, but we can take things to another level by making the message fade out and disappear after so many seconds. We’ll be using Spring MVC attributes to pass the message, ThymeLeaf, the Handlebars jQuery Plugin and an old-fashioned jQuery .fadeOut() function to perform the disappearing act.

Passing Formatted Spring MVC Attributes

Here is the ContactController method to add a new contact. You’ll notice an addFeedbackMessage() call. This method isn’t shown but formats the messages.properties string according to the current locale and assigns it to a RedirectAttributes FlashAttribute named “feedbackMessage.” We’ll see that string name again.

ThymeLeaf Handles a Feedback Message

So we added a FlashAttribute to the model we returned to the client with

model.addFlashAttribute("feedbackMessage", localizedFeedbackMessage);

On our ThymeLeaf page we have a message-holder element ready and waiting for a feedbackMessage attribute.

Contact.js and the Handlebars Template

Finally in our Contact.JS Javascript file we are going to have Handlebars compile the following HTML template from our Thymeleaf page and replace the above message-holder <div /> contents.

Here’s the javascript.

The addMessage() function is triggered if the .messageblock CSS Class we saw in the Thymeleaf page earlier is present.

You’ll find the source code described in this post in NixMash Spring v0.1.5 on GitHub. You will also see a complete implementation of this technique in the source code that accompanies Petri Kainulainen’s excellent book Spring Data from Packt Publishing.