Spring MVC, JSON, CSRF, and a Bootstrap Multiselect Plugin

As I mentioned in my last post, we’re spending some time Client Side in NixMash Spring v0.2.x. Today we’re going to look at the role of Spring MVC, JSON and CSRF Tokens in the functions of the Bootstrap Multiselect JQuery Plugin from David Stutz. The widget serves no real function in our app other than demonstrate integrating Spring with Client Side functionality.

The Bootstrap Multiselect Plugin takes your basic <SELECT /> Control and gives it a few jazzy features. I took the Plugin and made a Bootstrap Badge out of it so we’re calling it Badge Boy. A “badge” component in Bootstrap is a number indicator beside a string (the “2” shown below.) We took the Badge metaphor to the extreme and are giving users the ability to select actual badges with which they want to award themselves.

To make Badge Boy a worthy widget we should at the very least make the data persistent for the user session and we may eventually do that, but for now we’re going to look at the following issues.

  1. Passing the selected values in JSON format to a Spring MVC method
  2. Configuring that Spring MVC method to receive the input and pass back a formatted message.properties value to the client
  3. Sending a CSRF token (Cross Site Request Forgery) to the server with the Ajax Http POST action

Passing selected values in JSON format to Spring MVC

You can read more about configuring the Multiselect Plugin so we’ll skip ahead to passing the selected values to Spring MVC. The Plugin has several javascript functions including onDropdownHidden which is triggered when the dropdown is closed. We’ll use that callback to pass the values to Spring MVC.

onDropdownHidden: function(event) {
var selectedBadgeValues = $('select#multiselect-badgeboy').val();

Here’s the JavaScript function to pass the updated values to the Spring MVC method.

The data passed will look like this.

Configuring the Spring MVC method

A couple things to point out here. Notice the @ResponseBody and @RequestBody annotations. With fasterxml.Jackson configured as our HttpMessageConverter our JSON needs are covered.

Also notice we’re retrieving the selected values as a List<String> to keep things simple. No need for a class object given the widget’s simple functionality.

Passing a CSRF Token

If you have Cross Site Request Forgery enabled and do an HttpMethod POST to a Spring MVC endpoint you’ll be hit with a 302 and a redirect to the login page. We don’t want to disable CSRF so we’re going to create a MetaTag and include it in our Request Header with Ajax calls. We’ll set that up in our Thymeleaf Header fragment.

Now we’re good to go as we see in our Web Page View Source. Our token is populated and sent with all of our Ajax requests.

All source code described in this post is available in the v0.2.1 branch of NixMash Spring on GitHub. It’s also on the NixMash Spring Demo Site, so go ahead and award yourself some badges!