Spring 4 MVC - JQuery Ajax form submit example



Spring 4 MVC - JQuery Ajax form submit example

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.

Spring 4 MVC - Form validation example | BORAJI.COM

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.

<dependencies>
   <!-- Spring MVC Dependency -->
   <dependency>
     <groupId>org.springframework</groupId>
     <artifactId>spring-webmvc</artifactId>
     <version>4.3.7.RELEASE</version>
   </dependency>
   
   <!-- Jackson API -->
   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.8.7</version>
   </dependency>
   
   <!-- Hibernate Validator -->
   <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-validator</artifactId>
     <version>5.4.1.Final</version>
   </dependency>
   
   <!-- JSTL Dependency -->
   <dependency>
     <groupId>javax.servlet.jsp.jstl</groupId>
     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
     <version>1.2.1</version>
   </dependency>
   <dependency>
     <groupId>taglibs</groupId>
     <artifactId>standard</artifactId>
     <version>1.1.2</version>
   </dependency>
   
   <!-- Servlet Dependency -->
   <dependency>
     <groupId>javax.servlet</groupId>
     <artifactId>javax.servlet-api</artifactId>
     <version>3.1.0</version>
     <scope>provided</scope>
   </dependency>
   
   <!-- JSP Dependency -->
   <dependency>
     <groupId>javax.servlet.jsp</groupId>
     <artifactId>javax.servlet.jsp-api</artifactId>
     <version>2.3.1</version>
     <scope>provided</scope>
   </dependency>
</dependencies>

 

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.

Employee.java

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.

EmployeeJsonRespone.java

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.

EmployeeController.java

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
 */
@Controller
public class EmployeeController {

   @GetMapping("/")
   public String employeeForm() {
      return "employeeForm";
   }

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

      EmployeeJsonRespone respone = new EmployeeJsonRespone();
      
      if(result.hasErrors()){
         
         //Get error message
         Map<String, String> errors = result.getFieldErrors().stream()
               .collect(
                     Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage)
                 );
         
         respone.setValidated(false);
         respone.setErrorMessages(errors);
      }else{
         // Implement business logic to save employee into database
         //..
         respone.setValidated(true);
         respone.setEmployee(employee);
      }
      return respone;
   }
}

 

JSP View

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

employeeForm.jsp

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

<style type="text/css">
  span.error{
    color: red;
    margin-left: 5px;
  }
</style>

<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
      e.preventDefault();
      
      //Remove all errors
      $('input').next().remove();
      
      $.post({
         url : 'saveEmployee',
         data : $('form[name=employeeForm]').serialize(),
         success : function(res) {
         
            if(res.validated){
               //Set response
               $('#resultContainer pre code').text(JSON.stringify(res.employee));
               $('#resultContainer').show();
            
            }else{
              //Set error messages
              $.each(res.errorMessages,function(key,value){
  	            $('input[name='+key+']').after('<span class="error">'+value+'</span>');
              });
            }
         }
      })
   });
});
</script>
</head>
<body>
  <h1>Employee Input Form</h1>
  <hr />

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

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

 

Spring configuration

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

WebConfig.java

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
 */

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

   @Bean
   public InternalResourceViewResolver resolver() {
      InternalResourceViewResolver resolver = new InternalResourceViewResolver();
      resolver.setViewClass(JstlView.class);
      resolver.setPrefix("/WEB-INF/views/");
      resolver.setSuffix(".jsp");
      return resolver;
   }
}

 

Servlet container initialization

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

MyWebAppInitializer.java

package com.boraji.tutorial.spring.config;

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

/**
 * @author imssbora
 */
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

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

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

   @Override
   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.

http://localhost:8080/

Spring 4 MVC - JQuery Ajax form submit example | BORAJI.COM

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

Spring 4 MVC - JQuery Ajax form submit example | BORAJI.COM

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

Spring 4 MVC - JQuery Ajax form submit example | BORAJI.COM