Changes to the Spring-MVC Course – now with added WebFlow!

We’re getting closer to releasing the Spring-MVC course and as we reach the end it’s becoming clear that some juggling is needed to the back end of the course.

Many people have contacted me to ask about Spring WebFlow, and whether we’ll be doing a course on it. I’d always planned to do a separate standalone course on this topic, but on reflection I’ve decided it would fit more naturally as a chapter on the Spring-MVC course itself.

The revised running order is now:

1: Introduction
2: An overview of MVC
3: First steps in Spring MVC
4: Mapping Parameters, Accessing Sessions
5: Internationalization (i18n)
6: Form Handling and Validation
7: Validation and JSR-303
8: Alternative views and Ajax
9: Spring WebFlow – the Basics
10: Going further with WebFlow

The chapter on Post-Redirect-Get was too small to stand on it’s own and is now part of the form handling chapter.

I think this outline is a bit tighter and more focussed, and with WebFlow included, will be much better value.

It does, however, mean a slight delay to allow time for scripting and recording of the more advanced material, but not a big one, we’re now on for Friday 6 August.

Working with Ajax and JSON in Spring-MVC

I’m now working on the final major chapter of the Spring-MVC course, how to use Ajax with Spring.

I must say I’m pretty shocked (in a good way) at just how simple the support for Ajax in Spring-MVC is.

On the course, we’re going perform a search against a database of books, and produce a list of near matches on the fly, as the user types into a text box on the web form. Something like this, with the results updating as soon as I type a letter in the search box…

I’d like to be able to send the list of matching books back to the web browser in JSON form. Although in the early days of Ajax, data was sent in XML form (the X in Ajax), these days JSON is a more natural choice as it is more compact and much easier to manipulate on the JavaScript client.

For details of what JSON looks like, see here. For example, a collection of book data might look something like:

[{"author":"Will Self","title":"Great Apes"},
 {"author":"Charles Dickens","title":"Great Expectations "},
 {"author":"Ken Kesey","title":"Sometimes a Great Notion "},
 {"author":"F. Scott Fitzgerald","title":"The Great Gatsby "}]

So I’d like my controller to be able to send back the results in the form of JSON. You might be thinking that I need to convert my Java objects manually – but in fact Spring-MVC makes it almost trivial:

  1. Annotate your controller method with @ResponseBody. This annotation tells Spring that the response to the browser should be serialised (ie converted from plain Java Objects into some kind of flattened, encoded structure).
  2. Add the JAR files from the Jackson project into your lib directory. Jackson is capabale of transforming object graphs into JSON form.
  3. You also need the <mvc:annotation-driven/> directive in your Spring wiring. By the time we do Ajax on the course, we’ll have added this already, but if you’re reading the blog separately from the course, you’ll need to make sure you’ve done this.

These three things combined tells Spring that we want to send the response back from the method annotated with @ResponseBody in the form of a JSON graph.

So, the controller looks wonderfully simple:

@RequestMapping("/looseSearch")
public @ResponseBody List&lt;Book&gt; performLooseSearch(@RequestParam("CHARS")String chars)
{
    return bookService.searchBooksByLooseMatch(chars);
}

In terms of Spring-MVC, that’s all there is to know. You now just need to code a front end capable of making an Ajax call. Until recently, the recommended approach in Spring was to use a framework like DWR – a framework that allowed us to call Java code as if it were a JavaScript method.

These days, however, the amazing jQuery library is the preferred choice. jQuery is a library that makes everyday JavaScript tasks such as making Ajax calls almost trivially easy.

Now, jQuery is beyond the scope of Spring-MVC so I can’t provide a tutorial here, but I can show a code fragment that demonstrates how to call our loose search:

&lt;head&gt;
   &lt;script type="text/javascript" src="/scripts/jquery-1.4.2.min.js" /&gt;
  
   &lt;script type="text/javascript"&gt; 
 
  function doSearch() {   
     $.getJSON("looseSearch.do", { CHARS: $('#searchBox').val() }, function(data) 
               {   
                  $('#results').text('');
    
                  for (var index in data) {
                     $('#results').append('&lt;p&gt;' + data[index].title + '&lt;/p&gt;'); 
                  }
               });
 }
   &lt;/script&gt;
&lt;/head&gt;

&lt;h1&gt;Loose Search Test&lt;/h1&gt;

&lt;input type="text" id="searchBox" onKeyUp="doSearch();"/&gt;

&lt;div id="results"&gt;
 Results will appear here...
&lt;/div&gt;

All you need to do is download the jquery JavaScript file from here and make sure it is picked up by your page.

All references to $ are jQuery calls.

On line 7, getJSON performs an Ajax call to the URL “looseSearch.do” – hence our controller will be run. The request parameter CHARS is populated with whatever is contained in the “searchBox” input field.

When (and if) a response is received by the server, the callback function that I’ve provided is invoked (lines 8-14). In the callback function, I simply clear the “results” div (line 9), and then I loop around the JSON results. For each element in the results, I extract the title and wrap it around a paragraph tag.

Line 21 ensures that the doSearch() function is called everytime I release a key in the input field.

If you’re interested in seeing this full example coded, the Spring-MVC video course is released on 30 July 2010. You can register an interest by sending a blank email to subscribe@virtualpairprogrammers.com, and don’t worry, we won’t use your email address for any purpose except for keeping you updated with new courses.