2011-10-17

jQuery UI Autocomplete + Spring MVC

jQuery UI offers a nice autocomplete component. In this short tutorial I will show you how to use it with Spring 3 MVC back end.

The view

Let's look at the view first. I'm using Velocity here and below you can only see a tiny bit of the file.
       <form method="post" action="">
           <table>
               <tr>
                   <td>Your name:</td>
                   <td>#springFormInput("reservation.userName" "")
                   </td>
                   <td>#springShowErrors("" "")
                   </td>
               </tr>
This will create an input field with an ID userName.

HTML metadata

<link type="text/css"

href="../css/humanity/jquery-ui-1.8.16.custom.css"
   rel="stylesheet" />
<link type="text/css" href="../css/basic.css" rel="stylesheet" />
<script type="text/javascript"

src="../js/jquery-1.6.2.min.js"></script>
<script type="text/javascript"

src="../js/jquery-ui-1.8.16.custom.min.js"></script>
<script>
   $(function() {
       $( "input:submit" ).button();
   });
</script>
<style>
   .ui-autocomplete-loading { background:

white url('../images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script type="text/javascript" src="../js/autocomplete.js"></script>
Only the last line is non-standard. That's my custom JS file.

autocomplete.js

That's my custom JS file based heavily on the example jQuery UI have on their site.
$(function() {
   $("#userName").autocomplete(
       {
           source : function(request, response) {
               $.ajax({
                   url : "names",
                   dataType : "json",
                   data : {
                       term : request.term
                   },
                   success : function(data) {
                       response($.map(data.names, function(item) {
                           return {
                               label : item.label,
                               value : item.label
                           }
                       }));
                   }
               });
           },
           minLength : 1
       });
});
Let's explain it step by step. On windows load, the nameless function will run. Using jQuery selector I'm selecting the HTML element with ID userName. Then I'm calling the autocomplete() function on it that will turn it into an autocomplete input. It accepts many parameters; here I only use source and minLength because they are sufficient.
minLength specifies the content length threshold for back end query trigger. 1 means you only have to type 1 character to get suggestions.
source declares a function to handle response. That gives us the flexibility we need to handle our JSON response which looks like that:
{"names":[{"label":"Michael","value":"1"},{"label":"Mike","value":"2"},{"label":"Mikey","value":"3"}]}
This bit:
$.map(data.names, function(item)
… selects the names field from the response. Then, we have to select the label and value. Label is what will be displayed in the suggestion box. Value is what will be ultimately selected. In my case I chose to ignore the returned value (which is a number, as you can see) and just use the label field.

Back end - the controller

@Controller
@RequestMapping("/names")
public class NamesController {

   private static final Logger log = LoggerFactory
           .getLogger(NamesController.class);

   @RequestMapping(method = RequestMethod.GET)
   public String getNames(Model model,
           @RequestParam(required = false) String term) {
       log.debug("getNames(\"{}\")", term);
       model.addAttribute("names", Arrays.asList(names));
       return "jsonNames";
   }

   private LabelValueTo[] names = new LabelValueTo[] {
           new LabelValueTo("Michael", "1"), new LabelValueTo("Mike", "2"),
           new LabelValueTo("Mikey", "3") };

}
I have already written a bit about Spring and JSON so I will not comment that in great detail. Notice that I'm returning a view called jsonNames. What happens with it next?

Back end - view resolvers

I have these 2 view resolvers declared (there is more configuration to it - to get it download the source).
    <bean class="org.springframework.web.servlet.view.XmlViewResolver">
       <property name="order" value="0" />
       <property name="location" value="/WEB-INF/views.xml" />
   </bean>

   <bean id="viewResolver"
       class="org.springframework.web.servlet.view.velocity.VelocityViewResolver">
       <property name="order" value="1" />
       <property name="cache" value="true" />
       <property name="prefix" value="/WEB-INF/vm/" />
       <property name="suffix" value=".vm" />
       <property name="exposeSpringMacroHelpers" value="true" />
   </bean>
And the referenced view.xml file:
<bean name="jsonNames"
       class="org.springframework.web.servlet.view.json.MappingJacksonJsonView" />

Summary

And that's it. I think it's pretty straightforward. Feel free to post comments and questions. Download the source from GitHub.

No comments:

Post a Comment