Jquery Ajax POST-GET Nested Objects to SpringBoot server

In this tutorial, JavaSampleApproach will guide you to implement a web application Jquery Ajax POST-GET Nested Objects to SpringBoot serverM.

Related posts:
How to integrate JQuery Ajax POST/GET & Spring MVC | Spring Boot
Ajax Jquery post List JavaScript Objects to SpringBoot server | BootStrap
JQuery uses Bootstrap Table to display data from SpringBoot RestAPI
JQuery Ajax Http Delete remove data from SpringBoot RestAPI

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.8.1.RELEASE
– JQuery
– Bootstrap
– Spring Boot – 1.5.7.RELEASE

II. Practice

In the tutorial, we build a SpringBoot project as below:

Jquery Ajax POST-GET Nested Objects to SpringBoot - project structure

Step to do:
– Create Spring Boot project
– Create data models
– Create 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

1. Create 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 Nested Objects to SpringBoot - add dependencies

Open pom.xml file and check needed dependencies:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. Create data models

– Create Address model:


package com.javasampleapproach.jqueryajax.model;

public class Address {
	 
	private String street;
	private String postcode;
	
	public Address(){}
	
	public Address(String street, String postcode){
		this.street = street;
		this.postcode = postcode;
	}
 
	public String getStreet() {
		return street;
	}
 
	public void setStreet(String street) {
		this.street = street;
	}
 
	public String getPostcode() {
		return postcode;
	}
 
	public void setPostcode(String postcode) {
		this.postcode = postcode;
	}
 
	@Override
	public String toString() {
		return "Address [street=" + street + ", postcode=" + postcode + "]";
	}
}

– Then create Customer model that includes Address model:


package com.javasampleapproach.jqueryajax.model;

public class Customer {
	 
	private String name;
	private Integer age;
	private Address address;
	
	public Customer(){}
	
	public Customer(String name, Integer age, Address address){
		this.name = name;
		this.age = age;
		this.address = address;
	}
 
	public String getName() {
		return name;
	}
 
	public void setName(String name) {
		this.name = name;
	}
 
	public Integer getAge() {
		return age;
	}
 
	public void setAge(Integer age) {
		this.age = age;
	}
 
	public Address getAddress() {
		return address;
	}
 
	public void setAddress(Address address) {
		this.address = address;
	}
 
	@Override
	public String toString() {
		return "Customer [name=" + name + ", age=" + age + ", address=" + address + "]";
	}
 
}

3. Create Response message


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);
		
		Response response = new Response("Done", customer);
		return response;
	}
}

6. Create an index.html view

<!DOCTYPE HTML>
 
<html>
<head>
	  <title>Spring Boot - AJAX POST GET Example</title>
	  <meta charset="utf-8" />
	  <meta name="viewport" content="width=device-width, initial-scale=1" />
	  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
	  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	  <script src="/js/postrequest.js"></script>
      <script src="/js/getrequest.js"></script>
</head>
<body>
 
<div class="container">
 
	<h3 style="color:blue">POST-GET AJAX NESTED OBJECT</h3>
	
	<div class="row col-md-6">
		<form id="customerForm">
			<div class="form-group">
				<label for="name">Name:</label>
				<input type="text" class="form-control" id="name" placeholder="Enter Name"/>
			</div>
			<div class="form-group">
				<label for="age">Age:</label>
				<input type="number" min="18" max="100" class="form-control" id="age" placeholder="Enter Age"/>
			</div>
			<div class="form-group">
				<label for="street">Street:</label>
				<input type="text" class="form-control" id="street" placeholder="Enter Street"/>
			</div>
			<div class="form-group">
				<label for="postcode">PostCode:</label>
				<input type="text" class="form-control" id="postcode" placeholder="Enter PostCode"/>
			</div>
			<button type="submit" class="btn btn-default">Submit</button>
		</form>
		
		<div id="postResultDiv" style="margin:10px 0px 10px 0px;">
		</div>
		
		<div>
		<button id="getAllCustomerId" type="button" class="btn btn-primary" style="margin:10px 0px 10px 0px;">Get All Customers</button>
		<div id="getResultDiv" style="margin:10px 10px 10px 15px;">
	        <ul class="list-group">
	    	</ul>
    	</div>
	</div>
	</div>
</div>
</body>
</html>

7. Create Ajax POST & GET requests

– 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 = {
    			name : $("#name").val(),
    			age : $("#age").val(),
    			address : {
    		    	street : $("#street").val(),
    		    	postcode : $("#postcode").val()
    		    }
    	}
    	
    	console.log("formData before post: " + formData);
    	
    	// 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!
" + "--> {name: " + result.data.name + ", age: " + result.data.age + ", street: " + result.data.address.street + ", postcode: " + result.data.address.postcode +"}

"); }else{ $("#postResultDiv").html("Error"); } console.log(result); }, error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); // Reset FormData after Posting resetData(); } function resetData(){ $("#name").val(""); $("#age").val(""); $("#street").val(""); $("#postcode").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 = "{name: " + customer.name + 
						", age: " + customer.age +
						", street: " + customer.address.street +
						", postcode: " + customer.address.postcode +"}";
						
						$('#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.
    –> Result:

    Jquery Ajax POST-GET Nested Objects to SpringBoot - result

    III. Sourcecode

    SpringBootJQueryAjaxClient



    By grokonez | October 19, 2017.

    Last updated on May 4, 2021.



    Related Posts


    3 thoughts on “Jquery Ajax POST-GET Nested Objects to SpringBoot server”

    Got Something To Say:

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

    *