Spring MVC 4 - JQuery Ajax form submit example

Posted on May 21, 2017

In this post, I will show you how to use the JQuery’s Ajax function to send the form data to a controller’s handler method.

We will use the Hibernate Validator framework for server side validation of a model object and JQuery framework for displaying error messages on input form.

Tools and technologies used for this example are –

  • Spring 4.3.7.RELEASE
  • Hibernate Validator 5.4.1.Final
  • Jackson-databind 2.8.7
  • JQuery 3.2.1
  • Eclipse Neon.3
  • Maven 3.3.9
  • JavaSE 1.8
  • Apache Tomcat  7.0.47 (Embedded)

Let us proceed to write a simple Spring MVC application to submit a form using JQuery ajax function.

Project structure

Review the following web project structure build using Maven.


Refer this article to learn - How to create a web project using maven build tool in eclipse IDE.

Jar dependencies

In pom.xml file of your maven project, add the dependencies below.

   <!-- Spring MVC Dependency -->
   <!-- Jackson API -->
   <!-- Hibernate Validator -->
   <!-- JSTL Dependency -->
   <!-- Servlet Dependency -->
   <!-- JSP Dependency -->

Model classes

Create an Employee model class, whose field names are annotated with Hibernate Validator constraint annotations.

We will use this class for binding from data to the model using @ModelAttribute annotation in controller's handler method.


package com.boraji.tutorial.spring.model;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

public class Employee {

   @NotEmpty(message="Enter first name.")
   private String firstName;

   @NotEmpty(message="Enter last name.")
   private String lastName;

   @Email(message="Enter a valid email.")
   private String email;

   @NotEmpty(message="Enter your designation.")
   private String designation;

   //Getter and Setter methods

Create another model class, name as EmployeeJsonRespone, for exposing the mode data in JSON format to view using the @ResponseBody annotation.


package com.boraji.tutorial.spring.model;

import java.util.Map;

public class EmployeeJsonRespone {
   private Employee employee;
   private boolean validated;
   private Map<String, String> errorMessages;

   // Getter and Setter methods

Controller class

Create a controller class to handle and validate the Ajax form data as follows.


package com.boraji.tutorial.spring.controller;

import java.util.Map;
import java.util.stream.Collectors;

import javax.validation.Valid;

import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.boraji.tutorial.spring.model.Employee;
import com.boraji.tutorial.spring.model.EmployeeJsonRespone;

 * @author imssbora
public class EmployeeController {

   public String employeeForm() {
      return "employeeForm";

   @PostMapping(value = "/saveEmployee", produces = { MediaType.APPLICATION_JSON_VALUE })
   public EmployeeJsonRespone saveEmployee(@ModelAttribute @Valid Employee employee,
         BindingResult result) {

      EmployeeJsonRespone respone = new EmployeeJsonRespone();
         //Get error message
         Map<String, String> errors = result.getFieldErrors().stream()
                     Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)
         // Implement business logic to save employee into database
      return respone;


JSP View

Create userForm.jsp file under src\main\webapp\WEB-INF\views folder to take user input.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<style type="text/css">
    color: red;
    margin-left: 5px;

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
   /*  Submit form using Ajax */
   $('button[type=submit]').click(function(e) {
      //Prevent default submission of form
      //Remove all errors
         url : 'saveEmployee',
         data : $('form[name=employeeForm]').serialize(),
         success : function(res) {
               //Set response
               $('#resultContainer pre code').text(JSON.stringify(res.employee));
              //Set error messages
  	            $('input[name='+key+']').after('<span class="error">'+value+'</span>');
  <h1>Employee Input Form</h1>
  <hr />

  <form action="saveEmployee" method="post" name="employeeForm">
        <td>First Name</td>
        <td><input name="firstName" type="text" /></td>
        <td>Last Name</td>
        <td><input name="lastName" type="text" /></td>
        <td><input name="email" type="text" /></td>
        <td><input name="designation" type="text" /></td>
        <td><button type="submit">Submit</button></td>

<!-- Result Container  -->
<div id="resultContainer" style="display: none;">
 <h4 style="color: green;">JSON Response From Server</h4>
  <pre style="color: green;">

Spring configuration

Create a web @Configuration class annotated with @EnableWebMvc and @ComponentScan as follows.


package com.boraji.tutorial.spring.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

 * @author imssbora

@ComponentScan(basePackages = { "com.boraji.tutorial.spring.controller" })
public class WebConfig extends WebMvcConfigurerAdapter {

   public InternalResourceViewResolver resolver() {
      InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      return resolver;

Servlet container initialization

Create a container initializer class by extending the AbstractAnnotationConfigDispatcherServletInitializer class as follows.


package com.boraji.tutorial.spring.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

 * @author imssbora
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

   protected Class<?>[] getRootConfigClasses() {
      return new Class[] {};

   protected Class<?>[] getServletConfigClasses() {
      return new Class[] { WebConfig.class };

   protected String[] getServletMappings() {
      return new String[] { "/" };


Build + Deploy + Run application

Use the following maven commands to build, deploy and run embedded Tomcat server.

mvn clean install  (This command triggers war packaging)

mvn tomcat7:run (This command run embedded tomcat and deploy war file automatically)

You can refer this link to learn how to run the above commands in Eclipse IDE.


Type the following URLs in browser's address bar to open the user input from.



On validation failure, employee input form with error messages will look like as follows.


On validation success, employee input form with JSON response will look like as follows.


Download Sources