Spring MVC + jQuery Integration Example

This tutorial demonstrates how to integrate Spring MVC and jQuery for developing a web application. This example uses jQuery front end for getting the data from Spring MVC controller. Also the data is used in the text box for the auto completion feature. If you have any questions, please write it in the comments section.

also read:

1. Spring MVC Controller

CompanyController.java
This is the implementation of Spring MVC controller which is accessed by the jQuery.

package javabeat.net.spring.mvc;

import java.util.List;

import org.springframework.stereotype.Controller;
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;
import org.springframework.web.servlet.ModelAndView;

import javabeat.net.spring.dao.DataStore;
import javabeat.net.spring.model.Company;

@Controller
public class CompanyController {
	private static DataStore dataStore = new DataStore();

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index() {

        Company userForm = new Company();

        return new ModelAndView("company", "companyForm", userForm);
    }

    @RequestMapping(value = "/get_ceos_list",
                    method = RequestMethod.GET,
                    headers="Accept=*/*")
    public @ResponseBody List<String> getCountryList(@RequestParam("term") String query) {
        List<String> countryList = dataStore.getCeosList(query);

        return countryList;
    }

    @RequestMapping(value = "/get_co_list",
                    method = RequestMethod.GET,
                    headers="Accept=*/*")
    public @ResponseBody List<String> getCoList(@RequestParam("term") String query) {
        List<String> countryList = dataStore.getCoList(query);

        return countryList;
    }
}

Company.java

package javabeat.net.spring.model;

public class Company {
	private String ceos;
	private String companies;
	public String getCeos() {
		return ceos;
	}
	public void setCeos(String ceos) {
		this.ceos = ceos;
	}
	public String getCompanies() {
		return companies;
	}
	public void setCompanies(String companies) {
		this.companies = companies;
	}
}

DataStore.java
Here we are storing few sample data that will be used by the controller.

package javabeat.net.spring.dao;

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

public class DataStore {
	private List<String> ceos;
    private List<String> companies;

    public DataStore() {

        String data = "Steve Jobs, Bill Gates, Dell, Larry Ellision, Lary Page, Sergy Brin";

        ceos = new ArrayList<String>();
        StringTokenizer token = new StringTokenizer(data, ",");

        while(token.hasMoreTokens()) {
            ceos.add(token.nextToken().trim());
        }

        String strTags = "Apple, Microsoft, Oracle, Google, Facebook, Twitter";
        companies = new ArrayList<String>();
        StringTokenizer token2 = new StringTokenizer(strTags, ",");

        while(token2.hasMoreTokens()) {
            companies.add(token2.nextToken().trim());
        }

    }

    public List<String> getCeosList(String query) {

        String country = null;
        query = query.toLowerCase();
        List<String> matched = new ArrayList<String>();
        for(int i=0; i < ceos.size(); i++) {
            country = ceos.get(i).toLowerCase();
            if(country.startsWith(query)) {
                matched.add(ceos.get(i));
            }
        }
        return matched;
    }

    public List<String> getCoList(String query) {
        String country = null;
        query = query.toLowerCase();
        List<String> matched = new ArrayList<String>();
        for(int i=0; i < companies.size(); i++) {
            country = companies.get(i).toLowerCase();
            if(country.startsWith(query)) {
                matched.add(companies.get(i));
            }
        }
        return matched;
    }
}

2. Views using JQuery

company.jsp
Here is the important part where we are using the jQuery to hit the server. Note that the data is binded to the text box using the .autocomplete event.

<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring MVC Auto Complete with JQuery</title>
<link rel="stylesheet" type="text/css"
	href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />

<script type="text/javascript"
	src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript"
	src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>

</head>
<body>

	<h2>Spring MVC Autocomplete with JQuery</h2>
	<form:form method="post" action="submit" modelAttribute="companyForm">
		<table>
			<tr>
				<th>CEOs</th>
				<td><form:input path="ceos" id="ceos" /></td>
			</tr>
			<tr>
				<th>Companies</th>
				<td><form:input path="companies" id="companies" /></td>
			</tr>
			<tr>
				<td colspan="2"><input type="submit" value="Save" /> <input
					type="reset" value="Reset" /></td>
			</tr>
		</table>
		<br />

	</form:form>

	<script type="text/javascript">
function split(val) {
    return val.split(/,\s*/);
}
function extractLast(term) {
    return split(term).pop();
}

$(document).ready(function() {

    $( "#ceos" ).autocomplete({
        source: '${pageContext.request.contextPath}/get_ceos_list'
    });

    $( "#companies").autocomplete({
        source: function (request, response) {
            $.getJSON("${pageContext.request.contextPath}/get_co_list", {
                term: extractLast(request.term)
            }, response);
        },
        search: function () {
            var term = extractLast(this.value);
            if (term.length < 1) {
                return false;
            }
        },
        focus: function () {
            return false;
        },
        select: function (event, ui) {
            var terms = split(this.value);
	        terms.pop();
            terms.push(ui.item.value);
            terms.push("");
            this.value = terms.join(", ");
            return false;
        }
    });

});
</script>

</body>
</html>

3. Spring MVC Configurations

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd


http://www.springframework.org/schema/mvc


http://www.springframework.org/schema/mvc/spring-mvc.xsd


http://www.springframework.org/schema/context


http://www.springframework.org/schema/context/spring-context-3.0.xsd">

	<context:component-scan base-package="javabeat.net.spring.mvc" />
	<mvc:annotation-driven />
	<bean id="jspViewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
	</bean>

</beans>

4. Deployment Configurations

web.xml

<?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" 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">
  <display-name>SpringExamples</display-name>
	<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>/</url-pattern>
	</servlet-mapping>
</web-app>

5. Run Spring MVC + jQuery Application

You can access the above application after deploying to your web server. You would see the screen like below. When you type the letters in the text box, you would get the suggestions drop down.

spring mvc jquery demo

Download Source Code

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*