How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot

In this tutorial How to integrate JQuery Ajax POST/GET & Spring Boot Web Service, Grokonez will show you how to exchange data between Web client and Spring Boot Web Services.

Related Posts:
How to integrate Http Angularjs & Spring Boot
Spring Web MVC – Spring Form Submission | Spring Boot
Jquery Ajax POST-GET Nested Objects to SpringBoot server


I. Technologies for JQuery Ajax POST/GET & Spring Boot tutorial

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– JQuery
– BootStrap
– Spring Boot – 1.5.7.RELEASE

II. Overview

1. Project Structure

jquery ajax post get spring boot - project structure

In How to integrate JQuery Ajax POST/GET & Spring Boot Web Service, we create 2 Ajax requests: POST & GET

2. Step to do

– Create Spring Boot project
– Create simple model
– Create simple Response message
– Create Web Controller to provide web views
– Create RestController for POST & GET requests
– Create an index.html view
– Create Ajax POST & GET requests
– Run & Check results

III. Practices

1. Create a Spring Boot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, add project info, then press Next for needed dependencies:
For Template Engines, choose Thymeleaf
For Web MVC, choose Web->Web

jquery ajax post get spring boot - dependencies

Open pom.xml file and check needed dependencies:


	org.springframework.boot
	spring-boot-starter-thymeleaf


	org.springframework.boot
	spring-boot-starter-web


2. Create simple model

Create a Customer model:

package com.javasampleapproach.jqueryajax.model;

public class Customer {
    private String firstname;
    private String lastname;
     
    public Customer(){}
     
    public Customer(String firstname, String lastname){
        this.firstname = firstname;
        this.lastname = lastname;
    }
     
    // firstname
    public String getFirstname() {
        return firstname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
     
    // lastname
    public String getLastname() {
        return lastname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
}

3. Create simple Response message

Create a simple message: Response

package com.javasampleapproach.jqueryajax.message;

public class Response {
	private String status;
	private Object data;
	
	public Response(){
		
	}
	
	public Response(String status, Object data){
		this.status = status;
		this.data = data;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public Object getData() {
		return data;
	}

	public void setData(Object data) {
		this.data = data;
	}
}

4. Create Web Controller to provide web views

package com.javasampleapproach.jqueryajax.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class WebController {
	
    @GetMapping(value="/")
    public String homepage(){
        return "index";
    }
}

5. Create RestController for POST & GET requests

package com.javasampleapproach.jqueryajax.controller;

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

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javasampleapproach.jqueryajax.message.Response;
import com.javasampleapproach.jqueryajax.model.Customer;

@RestController
@RequestMapping("/api/customer")
public class RestWebController {

	List cust = new ArrayList();

	@GetMapping(value = "/all")
	public Response getResource() {
		Response response = new Response("Done", cust);
		return response;
	}

	@PostMapping(value = "/save")
	public Response postCustomer(@RequestBody Customer customer) {
		cust.add(customer);
		
		// Create Response Object
		Response response = new Response("Done", customer);
		return response;
	}
}

6. Create index.html view

Simple index.html is created with Bootstrap & Thymeleaf


 


	  Spring Boot - AJAX POST GET Example
	  
	  
	  %MINIFYHTMLc05cfe25a9bd376b2c3356911fc10f2f18%%MINIFYHTMLc05cfe25a9bd376b2c3356911fc10f2f19%%MINIFYHTMLc05cfe25a9bd376b2c3356911fc10f2f20%%MINIFYHTMLc05cfe25a9bd376b2c3356911fc10f2f21%

 

POST-GET AJAX Example

%MINIFYHTMLc05cfe25a9bd376b2c3356911fc10f2f22%

7. Create Ajax POST & GET JavaScript

– Create a POST request by JQuery Ajax in postrequest.js file:

$( document ).ready(function() {
	
	// SUBMIT FORM
    $("#customerForm").submit(function(event) {
		// Prevent the form from submitting via the browser.
		event.preventDefault();
		ajaxPost();
	});
    
    
    function ajaxPost(){
    	
    	// PREPARE FORM DATA
    	var formData = {
    		firstname : $("#firstname").val(),
    		lastname :  $("#lastname").val()
    	}
    	
    	// DO POST
    	$.ajax({
			type : "POST",
			contentType : "application/json",
			url : window.location + "api/customer/save",
			data : JSON.stringify(formData),
			dataType : 'json',
			success : function(result) {
				if(result.status == "Done"){
					$("#postResultDiv").html("

" + "Post Successfully!
" + "---> Customer's Info: FirstName = " + result.data.firstname + " ,LastName = " + result.data.lastname + "

"); }else{ $("#postResultDiv").html("Error"); } console.log(result); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#firstname").val(""); $("#lastname").val(""); } })

– Create a GET request by JQuery Ajax in getrequest.js:

$( document ).ready(function() {
	
	// GET REQUEST
	$("#getAllCustomerId").click(function(event){
		event.preventDefault();
		ajaxGet();
	});
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : window.location + "api/customer/all",
			success: function(result){
				if(result.status == "Done"){
					$('#getResultDiv ul').empty();
					var custList = "";
					$.each(result.data, function(i, customer){
						var customer = "- Customer with Id = " + i + ", firstname = " + customer.firstname + ", lastName = " + customer.lastname + "
"; $('#getResultDiv .list-group').append(customer) }); console.log("Success: ", result); }else{ $("#getResultDiv").html("Error"); console.log("Fail: ", result); } }, error : function(e) { $("#getResultDiv").html("Error"); console.log("ERROR: ", e); } }); } })

8. Run & Check results

Build & Run project with Spring Boot mode.
Results:

jquery ajax post get spring boot results

IV. Sourcecode

SpringBootJQueryAjaxClient



By grokonez | January 17, 2017.

Last updated on March 18, 2019.



Related Posts


18 thoughts on “How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot”

  1. I’m having difficulty understanding what the URL value should be.
    In your sample code you have it as:
    url : window.location + “api/customer/save”,
    I understand where you are getting api/customer/save but am unsure as to what window.location is. In addition I don’t understand exactly what the goal is for the URL statement.

    Thanks

    1. Hi Mark,

      window.location is used to get the current page address (URL).
      In the case, you can NOT use it.

      Regards,
      JSA

    1. Hi Raja,

      You can do it! You can use JSP or Thymeleaf view technologies to render data model on server side then returns response with html data to browser.

      Regards,
      JSA

  2. what does \all and \save url came unlike customer which is class name. can we give any name and use it same in ajax?
    if add /all to browser link will it work as get request and /save for post with out typing button.

Got Something To Say:

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

*