AngularJs JsonP request to cross domain | Springboot RestAPI & BootStrap

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

Related posts:
AngularJs CrossSite HTTP Requests to SpringBoot RestAPIs
AngularJs Table display Data Objects from RestAPIs remote | SpringBoot & BootStrap
Jquery 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. AngularJs JsonP and SpringBoot

JSONP is a solution to resolve cross-domain issues which uses script tag instead XMLHttpRequest object.

With AngularJs, we can use it as below:

function getAllCustomer(){
	// get URL
	var url = "http://localhost:9000/api/customer/all";
	var trustedUrl = $sce.trustAsResourceUrl(url);
	
	// do getting with JSON-P
	$http.jsonp(trustedUrl, {jsonpCallbackParam: 'jsaJsonpCallback'}).then(function (response) {
		$scope.getDivAvailable = true;
		$scope.listCustomers = response.data;
	}, function error(response) {
		$scope.postResultMessage = "Error Status: " +  response.statusText;
	});
}	

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:

angularjs jsonp to cross domain request with springboot restapi - response

III. Practice

We create 2 SpringBoot projects as below:

angularjs jsonp to cross domain request with springboot restapi - project structure

Steps to do:

– Implement AngularJs Front-end

  • Create SpringBoot project
  • Create Web Controller
  • Create index.html file
  • Implemnt AngularJs controller

– 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 SpringBootAngular 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




	  AngularJs PUT Form Nested Object to SpringBoot Example
	  
	  %MINIFYHTML404405198141fa678ed518d5e056137616%%MINIFYHTML404405198141fa678ed518d5e056137617%



Customer List:

No Name Age Street PostCode
{{ $index + 1 }} {{ cust.name | uppercase}} {{ cust.age}} {{ cust.address.street}} {{ cust.address.postcode}}
%MINIFYHTML404405198141fa678ed518d5e056137618%
1.4 Implemnt AngularJs controller
var app = angular.module('app', []);

//#######################
//JSA CONTROLLER
//#######################

app.controller('jsaController', function($sce, $scope, $http, $location) {
	$scope.listCustomers = [];
	
	// $scope.getAllCustomer = 
	function getAllCustomer(){
		// get URL
		var url = "http://localhost:9000/api/customer/all";
		var trustedUrl = $sce.trustAsResourceUrl(url);
		
		// do getting with JSON-P
		$http.jsonp(trustedUrl, {jsonpCallbackParam: 'jsaJsonpCallback'}).then(function (response) {
			$scope.getDivAvailable = true;
			$scope.listCustomers = response.data;
		}, function error(response) {
			$scope.postResultMessage = "Error Status: " +  response.statusText;
		});
	}
	
	getAllCustomer();
});
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:

angularjs jsonp to cross domain request with springboot restapi - results

angularjs jsonp to cross domain request with springboot restapi - request header

angularjs jsonp to cross domain request with springboot restapi - response

IV. Sourcecode

SpringBootAngular
SpringBootJsonpRestAPI



By grokonez | November 6, 2017.


Related Posts


1 thought on “AngularJs JsonP request to cross domain | Springboot RestAPI & BootStrap”

  1. Love your site. I am porting my skill set from basic VBA to XHR and onward to jQuery. Do you have any tutorials on how to interact / browser automation with XHR without mixing IE automations?

Got Something To Say:

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

*