Archive

Archive for the ‘jQuery’ Category

jQuery Autocomplete example with Spring MVC

First create Spring REST controller to process the request.


@RestController
@RequestMapping(value = "/json")
public class RESTController
{

@ResponseBody
@RequestMapping(value = "/city", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public Response<List<SearchBean>> getStateList( @RequestParam("term") String term, Locale locale )
{

Response<List<SearchBean>> returnResponse = null;
List<City> cityList = null;
List<SearchBean> suggestCityList = null;
String cityName = "";
SearchBean searchBean = null;
try
{
cityList = new ArrayList<City>();
suggestCityList = new ArrayList<SearchBean>();
cityList = Data.getCityList( locale );  // load city Objects list

for ( City city : cityList )
{
cityName = city.getName();
if ( ( cityName.toLowerCase( locale ).startsWith( term.toLowerCase( locale ) )   )
{
searchBean = new SearchBean();
searchBean.setLabel( cityName );
suggestCityList.add( searchBean );
}
}
returnResponse = new Response<>( suggestCityList, "", Response.SUCCESS );
}
catch ( CustomGenericException e )
{
// TODO: handle exception

returnResponse = new Response<>( null, "", Response.ERROR );
}
return returnResponse;

}

}

SearchBean class is just a pojo class with two parameters.

now , initialize the autocomplete function.


function loadSmartkeySuggestion(element,_url,minLength,dataType){$(element).autocomplete({

source: function( request, response ) {
$.ajax({
url:_url ,
dataType: dataType,
data: {
term: request.term
},
success: function( data ) {
if(data.status == 1) // if data is available
response( data.data );
}
});
},
minLength: minLength

});}

Categories: jQuery, Spring Tags: