Spring MVC jQuery Autocomplete

Spring MVC jQuery Autocomplete

It is very important for project to provide auto-complete functionality based on data user enters into the input field. Autocomplete is functionality which makes asynchronous AJAX call to the server and fetch the result based on the user input and show the results. This demo will show you how to achieve autocomplete functionality using jQuery with Spring MVC framework.

Important point when return data as List:

  • Include annotation driven tag in dispatcher-servlet.xml (Spring context configuration) as below:
<mvc:annotation-driven />

 

  • If your controller method is annotate with @ResponseBody then Spring transforms returned data type into JSON format
  • @ResponseBody automatically encodes object in appropriate formats based on accept header of request and presence of JSON or XML libraries in classpath.
  • To encode data in appropriate format you will have to include JSON parser in your class path which will convert return data in appropriate format. For example I am using Jackson parser below is maven dependency that needs to be included in you pom.xml file and if you are using simple eclipse project then include jackson-mapper-aslxxx.jar in your class path.

Below are needed:

  • Eclipse 3.0 or above (Download from here)
  • JDK 1.6 or above (Download from here )
  • Tomcat 6 or above (Please follow link to install and configure tomcat in eclipse: Configure and Run Tomcat server in eclipse )
  • Maven 3.0.4
  • Jackson JSON dependencies in pom.xml

After all set up and configuration you will below autocomplete functionality in browser: 

Spring MVC jQuery Autocomplete

  • Create maven project SpringAutoCompletein eclipse (Please use this link if you are not familiar how to create maven project in eclipse: Create maven Project Eclipse)
  • Below shows project structure:

Spring MVC jQuery Autocomplete

 

  • Please add below dependency in pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.javahonk</groupId>
    <artifactId>SpringPaginationDataTables</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringAutocomplete Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <spring.version>4.0.3.RELEASE</spring.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>       

    </dependencies>
    <build>
        <finalName>SpringAutocomplete</finalName>
    </build>
</project>

  • Please copy below XML into your web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.web</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <welcome-file-list>  
       <welcome-file>helloWorld.web</welcome-file>
    </welcome-file-list>

</web-app>
  • Now create file name: dispatcher-servlet.xml inside WEB-INF folder and copy and paste below content
<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
         
     
    <context:component-scan base-package="com.javahonk.controller" />  
 
    <mvc:annotation-driven />
 
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
    
</beans>
  • Create jsp folder inside WEB-INF folder
  • Create jsp file name: helloWorld.jsp and copy paste below code:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<title>Spring Auto-complete</title>
<script type="text/javascript">

    $(function() {      
        $("#tagsName").autocomplete({
            source: function (request, response) {
                $.getJSON("${pageContext.request.contextPath}/getMachedNames.web", {
                    term: request.term
                }, response);
            }
        });
    });
    
</script>
</head>
<body>
<form:form method="get" action="">
    <h1>${message}</h1>
    Enter Name: <input id="tagsName">
    
</form:form>    
</body>
</html>
  • Create package name com.javahonk.controller inside src/main/java folder
  • Create class name: DataCache.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller;

import java.util.ArrayList;
import java.util.List;

public class DataCache {
    
    static StringBuilder dataCache;
    static String [] data;
    static{
    
    dataCache = new StringBuilder();
    dataCache.append("Aaron Hank,Abagnale Frank,Abbey Edward,Abel Reuben,Abelson Hal,"
        + "Abourezk James,Abrams Creighton,Ace Jane,Ba Jin,Baba Meher,Baba Tupeni,"
        + "Babbage Charles,Babbitt Milton,Bacevich Andrew,Bach Richard,Bachelard Gaston,"
        + "Bachelot Roselyne,Bacon Francis,Baddiel David,Baden-Powell Sir Robert (B-P),"
        + "Badiou, Alain,Badnarik, Michael,Cabell James Branch,Caesar Irving,Caesar Julius,"
        + "Cage John,Cain Peter,Callaghan James,Calvin John,Cameron Julia,Cameron Kirk,"
        + "Java Honk,Java Honk Test,Java Honk Test Successful,Java Honk Spring MVC,"
        + "Java Honk autocomplete,Java Honk Spring MVC autocomplete List");
    
    data =dataCache.toString().split(",");
    }
    
    public static List<String> getName(String name) {

    List<String> returnMatchName = new ArrayList<String>();
    String [] data =dataCache.toString().split(",");    
    for (String string : data) {
        if (string.toUpperCase().indexOf(name.toUpperCase())!= -1) {
        returnMatchName.add(string);
        }
    }
    
    return returnMatchName;
    }

}

  • Create class name: SpringMVCController.java inside com.javahonk.controller pakcage and copy paste below content in it:
package com.javahonk.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class SpringMVCController {
    @RequestMapping(value = "/helloWorld.web", method = 
        RequestMethod.GET)
    public String printWelcome(ModelMap model, HttpServletRequest 
        request, HttpServletResponse response) {

    model.addAttribute("message", "Spring MVC jQuery"
        + " Autocomplete");
    return "helloWorld";

    }
    

    @RequestMapping(value = "/getMachedNames.web", method = 
        RequestMethod.GET)
    public @ResponseBody
    List<String> getMachedNames(@RequestParam("term") String name){
    
    List<String> matchName = DataCache.getName(name);

    return matchName;
    }
}

 

  • Now lets run this set up in tomcat server. If you haven’t done tomcat set up in eclipse yet please use this link: Configure and Run Tomcat server in eclipse. Now right click project –>Run As –> Run on server you will see below screen with input field. Enter data in input field to send request and get java list format autocomplete asynchronous response from server:

Spring MVC jQuery Autocomplete

 

download Download Project: SpringAutocomplete

That’s it Spring MVC jQuery Autocomplete

2 thoughts on “Spring MVC jQuery Autocomplete”
  1. Thanks For a great Tutorial .
    in my case , it started working by above code after a small change in controller.
    ——————————————————————
    @RequestMapping(value = “/getMachedNames.web”, method = RequestMethod.GET,headers=”Accept=*/*”)
    public @ResponseBody List getMachedNames(@RequestParam(“term”) String name){

    }
    ———————————————————————

    RequestMethod.GET,headers=”Accept=*/*” is required to add in controller . Hope it will help someone .

    Thanks
    Anurag

Leave a Reply

Your email address will not be published. Required fields are marked *