Angular JS Spring MVC Rest CRUD JSON Example using $http - Java @ Desk

Thursday, February 9, 2017

Angular JS Spring MVC Rest CRUD JSON Example using $http

Angular JS Spring MVC Rest CRUD JSON Example using $http

In this example, we will learn how to get the json data from rest service controller from Spring and display using the ng-model attribute of angular JS.

Spring RestController returns the Customer java object in JSON format and data is displayed on UI using angular JS. Call to the rest api is done using the $http of angular JS.

Following components will be used
1) Spring RestController
2) Angular JS ng-app
3) Angular JS ng-controller
4) Angular JS ng-model
5) Angular JS $http

Here are the files that are used.

public class Customer {

 private String name;
 private String id;

 public String getName() {
  return name;

 public void setName(String name) { = name;

 public String getId() {
  return id;

 public void setId(String id) { = id;


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

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@CrossOrigin(maxAge = 3600)
public class SpringRestController {

 @RequestMapping(method = RequestMethod.GET, path = "/customers", produces = MediaType.APPLICATION_JSON_VALUE)
 public ResponseEntity<Customer> getCustomers() {
  System.out.println("Entered in Get Customers");
  List<Customer> customers = new ArrayList<Customer>();
  Customer customer = new Customer();
  Gson gson = new Gson();
  return new ResponseEntity<Customer>(customer, HttpStatus.OK);

<!DOCTYPE html>
<html ng-app="customerApp">
<title>Customer App</title>
<script src="js/angular.js"></script>
<script src="js/customerController.js"></script>
<script src="js/jquery.min.js"></script>

 <div ng-controller="customerController">
   Customer Id - <input type="text" ng-model="" />
   Customer Name - <input type="text" ng-model="" />

var app = angular.module('customerApp', []);
app.controller("customerController", function($scope, $http) {
   function successCallback(response) {
          $scope.customer = {name:, id:};
   }, function errorCallback(response) {

No comments:

Post a Comment