Spring AJAX JQuery example

Spring AJAX JQuery example

This demo will show you how to pass data by onclick event through AJAX to Spring MVC controller and return back data to client. For converting Java to JSON and JSON to java we are using Jackson JSON processor which is already included in project which you could download from the bottom.

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 )
  • Spring jars which is already included in project for download in the bottom
  • Jackson JSON jars also included in project ( You cold also download from Jackson site here)

After all set up and configuration you will see below screen:

Spring AJAX JQuery example

 

  • Create dynamic web project in eclipse name: SpringMVCAJAX (Please use this link if you are not familiar how to create dynamic project in eclipse: Create Dynamic Web Project Eclipse)
  • Below shows project structure:

Spring MVC AJAX JQuery example

 

  • 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
<beans xmlns="http://www.springframework.org/schema/beans"
    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/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.controller" />

    <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 package name com.controller inside src folder
  • Create class name: SpringMVCController.java inside com.controller pakcage and copy paste below content in it
package com.controller;

import java.io.IOException;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
public class SpringMVCController {

    @RequestMapping(value = "/helloWorld.web", method = 
            RequestMethod.GET)
    public String printWelcome(@ModelAttribute("person") 
    Person person,BindingResult result, ModelMap model, 
    HttpServletRequest request,
            HttpServletResponse response) {

        model.addAttribute("message", "AJAX JQuery example");
        return "helloWorld";

    }

    @RequestMapping(value = "/validateCaptchaThroughAJAX.web", 
            method = RequestMethod.POST)
    @ResponseBody
    public String validateCaptchaThroughAJAX(@RequestBody 
            String json)
            throws IOException {

        ObjectMapper mapper = new ObjectMapper();
        Person requesValue = mapper.readValue(json, 
                Person.class);
        Person person = new Person();
        person.setName(requesValue.getName());
        person.setLocation(requesValue.getLocation());

        String viewName = "Success";
        if (viewName.equalsIgnoreCase("Success")) {
            person.setValidation("Success");
        } else {
            person.setValidation("Error");
        }

        return toJson(person);
    }

    private String toJson(Person person) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            String value = mapper.writeValueAsString(person);
            // return "["+value+"]";
            return value;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }

}

 

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

public class Person {
    
    private String validation;
    private String name;
    private String location;
    
    public String getValidation() {
        return validation;
    }
    public void setValidation(String validation) {
        this.validation = validation;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }   

}

 

  • Create jsp folder inside WEB-INF folder
  • Create jsp file name: helloWorld.jsp and copy paste below content in it
<%@ 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">
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<title>Spring AJAX and JQuery</title>
<script type="text/javascript">

function checkAjaxCall(){
    
    var name = $('#name').val(); 
    var location = $('#location').val(); 
    var json = {"name" : name,"location" : location};  
    $.ajax({
        url: "validateCaptchaThroughAJAX.web",
        type: 'POST',
        data: JSON.stringify(json),
        cache:false,
        beforeSend: function(xhr) {  
            xhr.setRequestHeader("Accept", "application/json");  
            xhr.setRequestHeader("Content-Type", "application/json");  
        },
        success:function(response){
            alert("Validation: "+response.validation+"   Name: "+response.name+"  Location: "+response.location);
        },
        error:function(jqXhr, textStatus, errorThrown){
            alert(textStatus);
        }
    });
    return true;
}

</script>
</head>
<body>
<form:form commandName="person" method="post" action="">
    <h1>Spring: ${message}</h1>
    <p>Name: <form:input path="name" id="name"/></p>
    <p>Location: <form:input path="location" id="location"/></p>
    <p><input type="button" name="Submit" value="Submit" onclick="checkAjaxCall();"></p>
    
</form:form>    
</body>
</html>

 

  • 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 as below:

Spring AJAX JQuery example

 

  • Finally you should see below screen. Enter name and location and click submit button:

Spring AJAX JQuery example

 

  • You will see data you entered in input box in alert message with success message below:

Spring AJAX JQuery example

download Download Project: Spring MVC AJAX JQuery example

That’s it Spring AJAX JQuery example completed.

2 thoughts on “Spring AJAX JQuery example”

Leave a Reply

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