Jquery JsonP request to cross domain | Springboot RestAPI & BootStrap

In the past posts, we had experiences with AngularJs CrossSite HTTP Requests and AngularJs JsonP. In the tutorial, JavaSampleApproach will show you how to use JQuery JsonP Request without worrying about cross-domain issues.

Related posts:
JQuery uses Bootstrap Table to display data from SpringBoot RestAPI
AngularJs CrossSite HTTP Requests to SpringBoot RestAPIs
AngularJs JsonP request to cross domain | Springboot RestAPI & BootStrap

I. Technologies

– Java 1.8
– Maven 3.6.1
– Spring Tool Suite – Version 3.9.0.RELEASE
– AngularJS
– Bootstrap
– Spring Boot – 1.5.7.RELEASE

II. Jquery JsonP and SpringBoot

JSONP is a solution to resolve cross-domain issues which uses script tag instead XMLHttpRequest object.
With JQuery, we can use it as below:

$.ajax({
	type : "GET",
	url : "http://localhost:9000/api/customer/all",
	
    // The callback parameter
    jsonp: "jsaJsonpCallback",
	
    // Tell jQuery that we're expecting JSON-P
    dataType: "jsonp",
    
	success: function(result){
		// do something here
	},
	error : function(e) {
		// do something here
	}
});	

To support JSON-P with SpringBoot RestAPI, we use AbstractJsonpResponseBodyAdvice:

@ControllerAdvice
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
 
    public JsonpControllerAdvice() {
        super("jsaJsonpCallback");
    }
}

Returned result is a Javascript object, NOT Json:

Jquery JsonP request to cross domain - Springboot RestAPI & BootStrap - results previews

III. Practice

We create 2 SpringBoot projects as below:

Jquery JsonP request to cross domain - Springboot RestAPI & BootStrap - projects

Steps to do:

– Implement AngularJs Front-end

  • Create SpringBoot project
  • Create Web Controller
  • Create index.html file
  • Implement Jquery Ajax

– Implement SpringBoot Backend

  • Create SpringBoot project
  • Create data models
  • Implement RestApi
  • Configure JsonpResponse advice

– Run and check results

1. Implement AngularJs Front-end
1.1 Create SpringBoot project

Use SpringToolSuite to create a SpringBoot project SpringBootJQueryJsonp with dependencies:


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


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

1.2 Create Web Controller
package com.javasampleapproach.angularjs.controller;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
@Controller
public class WebController {
 
	@GetMapping(value="/")
    public String homepage(){
        return "index";
    }
}
1.3 Create index.html file

 


      Spring Boot - DELETE-UPDATE AJAX Example
      
      %MINIFYHTML86f2ec9c2cbeeeb8c66058e01bfbc33216%%MINIFYHTML86f2ec9c2cbeeeb8c66058e01bfbc33217%%MINIFYHTML86f2ec9c2cbeeeb8c66058e01bfbc33218%

 

Customer Table

Id Name Age Street Postcode
%MINIFYHTML86f2ec9c2cbeeeb8c66058e01bfbc33219%
1.4 Implement Jquery Ajax
$(document).ready(function() {
	
	ajaxGet();
	
	// DO GET
	function ajaxGet(){
		$.ajax({
			type : "GET",
			url : "http://localhost:9000/api/customer/all",
			
		    // The callback parameter
		    jsonp: "jsaJsonpCallback",
			
		    // Tell jQuery that we're expecting JSON-P
		    dataType: "jsonp",
		    
			success: function(result){
				$.each(result, function(index, customer){
					
					var customerRow = '' +
										'' + (parseInt(index) + 1) + '' +
										'' + customer.name.toUpperCase() + '' +
										'' + customer.age + '' +
										'' + customer.address.street + '' +
										'' + customer.address.postcode + '' +
									  '';
					
					$('#customerTable tbody').append(customerRow);
					
		        });
				
				$( "#customerTable tbody tr:odd" ).addClass("info");
				$( "#customerTable tbody tr:even" ).addClass("success");
			},
			error : function(e) {
				alert("ERROR: ", e);
				console.log("ERROR: ", e);
			}
		});	
	}
})
2. Implement SpringBoot Backend
2.1 Create SpringBoot project

Use SpringToolSuite to create a SpringBoot project SpringBootJsonPRestAPI with dependency:


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

2.2 Create data models

– Create Address model:

package com.javasampleapproach.jsonp.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 + "}";
	}
}

– Create Customer model:

package com.javasampleapproach.jsonp.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 + "}";
	}
 
}
2.3 Implement RestApi
package com.javasampleapproach.jsonp.restapi;
 
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import com.javasampleapproach.jsonp.model.Address;
import com.javasampleapproach.jsonp.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("Jack", 25, new Address("NANTERRE CT", "77471")));
        custStores.put(Long.valueOf(2), new Customer("Mary", 37, new Address("W NORMA ST", "77009")));
        custStores.put(Long.valueOf(3), new Customer("Peter", 18, new Address("S NUGENT AVE", "77571")));
        custStores.put(Long.valueOf(4), new Customer("Amos", 23, new Address("E NAVAHO TRL", "77449")));
        custStores.put(Long.valueOf(5), new Customer("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;
	}
}
2.4 Configure JsonpResponse advice
package com.javasampleapproach.jsonp.advice;
 
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
 
@ControllerAdvice
public class JsonpControllerAdvice extends AbstractJsonpResponseBodyAdvice {
 
    public JsonpControllerAdvice() {
        super("jsaJsonpCallback");
    }
}
3. Run and check results

Run 2 above SpringBoot projects. -> Results:

Jquery JsonP request to cross domain - Springboot RestAPI & BootStrap - results

Jquery JsonP request to cross domain - Springboot RestAPI & BootStrap - results - headers

Jquery JsonP request to cross domain - Springboot RestAPI & BootStrap - results previews

IV. Sourcecode

SpringBootJqueryJsonp
SpringBootJsonpRestAPI



By grokonez | November 7, 2017.


Related Posts


Got Something To Say:

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

*