Jquery Ajax PUT Nested Objects to SpringBoot server | Bootstrap

In this tutorial, JavaSampleApproach will show you way to implement a web application Jquery Ajax PUT Nested Objects to SpringBoot server.

Related posts:
AngularJs POST-GET Nested Objects to SpringBoot server
Jquery Ajax POST-GET Nested Objects to SpringBoot server
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 Put Nested Objects to SpringBoot server - project structure

Step to do:
– Create Spring Boot project
– Create data models
– Create Web Controller to provide web views
– Create RestController for GET/PUT requests
– Create an index.html view
– Create Ajax PUT & 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 Put Nested Objects to SpringBoot server - 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.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.model;

public class Customer {
	private Long id;
	private String name;
	private Integer age;
	private Address address;
	
	public Customer(){}
	
	public Customer(Long id, String name, Integer age, Address address){
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
	}
 
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}
	
	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 Web Controller to provide web views



package com.javasampleapproach.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class WebController {

	@GetMapping(value="/")
    public String homepage(){
        return "index";
    }
}

4. Create RestController for GET/PUT requests


package com.javasampleapproach.controller;

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

import javax.annotation.PostConstruct;

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

import com.javasampleapproach.model.Address;
import com.javasampleapproach.model.Customer;

@RestController
@RequestMapping("/api/customer")
public class RestAPIs {
	
	Map custStores = new HashMap();
	
	@PostConstruct
    public void initIt() throws Exception {
        custStores.put(Long.valueOf(1), new Customer(new Long(1), "Jack", 25, new Address("NANTERRE-CT", "77471")));
        custStores.put(Long.valueOf(2), new Customer(new Long(2), "Mary", 37, new Address("W-NORMA-ST", "77009")));
        custStores.put(Long.valueOf(3), new Customer(new Long(3), "Peter", 18, new Address("S-NUGENT-AVE", "77571")));
        custStores.put(Long.valueOf(4), new Customer(new Long(4), "Amos", 23, new Address("E-NAVAHO-TRL", "77449")));
        custStores.put(Long.valueOf(5), new Customer(new Long(5), "Craig", 45, new Address("AVE-N", "77587")));
    }
	 
	@GetMapping(value = "/all")
	public List getResource() {
		
		List custList = custStores.entrySet().stream()
		        .map(entry -> entry.getValue())
		        .collect(Collectors.toList());
		
		return custList;
	}
 
	@PutMapping(value = "/update/{id}")
	public Customer postCustomer(@PathVariable long id, @RequestBody Customer customer) {
		custStores.put(id, customer);
		return customer;
	}
}

5. Create an index.html view

<!DOCTYPE HTML>
 
<html>
<head>
      <title>Spring Boot - DELETE-UPDATE AJAX Example</title>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
	  <script src="/js/ajaxGet.js"></script>
      <script src="/js/ajaxPut.js"></script>      
	  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
</head>

<body>
<div class="container">
	<h1>Customer List</h1>
    <div id="customerlist">
    	<ul class="list-group">
		</ul>
    </div>

	<div id="updateCustomerId" class="row col-md-6" style="">
	<h3>Here to Edit Info of Customer: </h3>
	<form id="customizedForm" style='background-color:#7FA7B0; color:white; padding:20px 20px 20px 20px'>
	  <div class="form-group">
	    <label for="updateFormCustId">CustomerId</label>
	    <input type="text" class="form-control" id="updateFormCustId" disabled="disabled"></input>
	  </div>
	  <div class="form-group">
	    <label for="updateFormName">Name:</label>
	    <input type="text" class="form-control" id="updateFormName" />
	  </div>
	  <div class="form-group">
	    <label for="updateFormAge">Age:</label>
	    <input type="number" min="16" max="100" class="form-control" id="updateFormAge" />
	  </div>
	  <div class="form-group">
	    <label for="updateFormStreet">Street:</label>
	    <input type="text" class="form-control" id="updateFormStreet" />
	  </div>
	  <div class="form-group">
	    <label for="updateFormPostcode">Postcode:</label>
	    <input type="text" class="form-control" id="updateFormPostcode" />
	  </div>
	  <button type="submit" class="btn btn-default">Update</button>
	</form>
	
	<div id="putResultDiv" style="margin:10px 0px 10px 0px;">
	</div>
	
	</div>
</div>
</body>
</html>

6. Create Ajax PUT & GET requests

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


$(document).ready(function() {
	
	ajaxGet();
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : window.location + "api/customer/all",
			success: function(result){
				$.each(result, function(i, customer){
					
					var updateUrl=window.location + "api/customer/update/" + customer.id;
					
					// render a customer data form
					var customerInfo = '
' + '
' + '' + '' + '
' + '
' + '' + '' + '
' + '' + '' + '' + '' '
'; $('#customerlist .list-group').append(customerInfo) // default fill data of the first customer to update-form if(i==0){ $("#updateFormCustId").val(customer.id); $("#updateFormName").val(customer.name); $("#updateFormAge").val(customer.age); $("#updateFormStreet").val(customer.address.street); $("#updateFormPostcode").val(customer.address.postcode); } }); console.log("Success: ", result); }, error : function(e) { $("#customerlist").html("Error"); console.log("ERROR: ", e); } }); } })

– Create a PUT request in ajaxPut.js:


$(document).ready(function() {
	
	$(document).on('submit', 'form', function (e) {
		event.preventDefault();
		fillDetailsToUpdateForm($(this));
	})
	
	$("#customizedForm").submit(function(){
		event.preventDefault();
		ajaxPut();
	});
	
	function fillDetailsToUpdateForm(object){
		var custId = $(object).find("input[name='customerId']").val();
		var name = $(object).find("input[name='name']").val();
		var age = $(object).find("input[name='age']").val();
		var street = $(object).find("input[name='street']").val();
		var postcode = $(object).find("input[name='postcode']").val();
		
		$("#updateFormCustId").val(custId);
		$("#updateFormName").val(name);
		$("#updateFormAge").val(age);
		$("#updateFormStreet").val(street);
		$("#updateFormPostcode").val(postcode);
	}
	
	/*
	 * AJAX PUT updated-form
	 */
    function ajaxPut(){
    	// PREPARE FORM DATA
    	var formData = {
    			id: $("#updateFormCustId").val(),
    			name : $("#updateFormName").val(),
    			age : $("#updateFormAge").val(),
    			address : {
    		    	street : $("#updateFormStreet").val(),
    		    	postcode : $("#updateFormPostcode").val()
    		    }
    	}
    	
    	var id = $("#updateFormCustId").val();
    	
    	console.log("formData before PUT: " + formData);
    	
    	// DO PUT
    	$.ajax({
			type : "PUT",
			contentType : "application/json",
			url : window.location + "api/customer/update/" + id,
			data : JSON.stringify(formData),
			dataType : 'json',
			
			// SUCCESS response
			success : function(customer) {
				// Create successful message
				$("#putResultDiv").html("

" + "Put Successfully!
" + "--> {id: " + customer.id + "name: " + customer.name + ", age: " + customer.age + ", street: " + customer.address.street + ", postcode: " + customer.address.postcode +"}

"); // Again fill data to Update-Form $("#updateFormCustId").val(customer.id); $("#updateFormName").val(customer.name); $("#updateFormAge").val(customer.age); $("#updateFormStreet").val(customer.address.street); $("#updateFormPostcode").val(customer.address.postcode); // Update name of the updated customer on Customer List $('#custform_' + customer.id).find("input[name='name']").val(customer.name); $('#custform_' + customer.id).find("input[name='age']").val(customer.age); $('#custform_' + customer.id).find("input[name='street']").val(customer.address.street); $('#custform_' + customer.id).find("input[name='postcode']").val(customer.address.postcode); }, // ERROR response error : function(e) { alert("Error!") console.log("ERROR: ", e); } }); } })

7. Run & Check results

Build & Run project with Spring Boot mode.
–> Result:

Jquery Ajax Put Nested Objects to SpringBoot server - result

Jquery Ajax Put Nested Objects to SpringBoot server - data exchange

III. Sourcecode

SpringBootAjaxJQueryPut



By grokonez | October 23, 2017.

Last updated on May 6, 2021.



Related Posts


Got Something To Say:

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

*