Consume RESTful Web Service using AngularJS + Spring 4 REST + JSON with ngResource and $http Example
April 30, 2016
On this page we will provide how to consume RESTful web service using AngularJS, Spring 4 REST and JSON with ngResource and $http example. $http is a core AngularJS service which is used to call http request methods. To call http GET and POST methods, $http provides $http.get and $http.post. ngResource is high level abstraction for $http. ngResource is particularly used to interact with RESTful web services. ngResource module has $resource service which provides default methods like get, save, query, remove and delete to interact with RESTful web service. Here on this page we will provide how to consume RESTful web services. For the demo we will fetch a complete list of person as well as we will fetch person by id.
Contents
Software Used
Find the software used in our example.1. Java 8
2. Spring 4.2.5.RELEASE
3. Tomcat 8
4. Gradle
5. AngularJS 1.4.9
6. Eclipse
Project Structure in Eclipse
Find the project structure in eclipse.Spring and AngularJS Libraries
Find the gradle file to build the spring project.build.gradle
apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'war' archivesBaseName = 'spring4' version = '1' repositories { mavenCentral() } dependencies { compile 'org.springframework.boot:spring-boot-starter-web:1.3.3.RELEASE' providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:1.3.3.RELEASE' }
1. angular.min.js
2. angular-resource.min.js
Find the URL to get help to install libraries.
Consume RESTful Web Service using AngularJS ngResource
ngResource
module is dedicated to work with RESTful web service using JSON. ngResource
is a higher level of abstraction on $http
. ngResource
has $resource
service which provides default methods like get, save, query, remove and delete. Find the AngularJS code.
app-ngresource.js
var app = angular.module('myApp', ['ngResource']); app.factory('Person', ['$resource', function ($resource) { return $resource('http://localhost:8080/spring4-1/info/person/:personId', {personId: '@pid'}); }]); app.controller('PersonController', ['$scope', 'Person', function($scope, Person) { this.persons=[]; this.fetchAllPersons = function(){ this.persons = Person.query(); }; this.fetchPersonById = function(id){ this.persons[0] = Person.get({ personId: id}, function() { console.log(id); }); }; this.fetchAllPersons(); //this.fetchPersonById(2); }]);
http://localhost:8080/spring4-1/info/person.
And if personId has value, suppose 22, then the URL will be created as follows.
http://localhost:8080/spring4-1/info/person/22.
To fetch all person use
fetchAllPersons()
and to fetch person by ID use fetchPersonById()
method. Now find the view code.
page-ngresource.jsp
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title> Spring 4 REST + AngularJS </title> </head> <body ng-app="myApp"> <div ng-controller="PersonController as personCtrl"> <h1> Spring 4 REST + AngularJS </h1> <table> <tr><th>ID </th> <th>Name</th> <th>Location</th></tr> <tr ng-repeat="row in personCtrl.persons"> <td><span ng-bind="row.pid"></span></td> <td><span ng-bind="row.name"></span></td> <td><span ng-bind="row.location"></span></td> </tr> </table> </div> <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular.min.js"></script> <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular-resource.min.js"></script> <script src="${pageContext.request.contextPath}/app-resources/js/app-ngresource.js"></script> </body> </html>
ng-app: This directive is used to auto bootstrap AngularJS application.
ng-controller: It attaches a controller class to the view.
ng-bind: It replaces the text value of element with given expression.
Consume RESTful Web Service using AngularJS $http
$http
is a core AngularJS service. It is used to call HTTP request methods such as $http.get, $http.head, $http.post, $http.put, $http.delete. Here we will use $http.get
to consume RESTful web service. Find the AngularJS code.
app-http.js
var myApp = angular.module('myApp', []); myApp.controller('PersonController', function($scope, $http){ $scope.persons = []; $http.get('http://localhost:8080/spring4-1/info/person') .then(function (response){ $scope.persons = response.data; //For multiple row //$scope.persons[0] = response.data; //For single row console.log("status:" + response.status); }).catch(function(response) { console.error('Error occurred:', response.status, response.data); }).finally(function() { console.log("Task Finished."); }); });
http://localhost:8080/spring4-1/info/person
We need to enable below line of code.
$scope.persons = response.data;
And to get a single person by id, suppose 2, with the URL
http://localhost:8080/spring4-1/info/person/2
Enable below line of code.
$scope.persons[0] = response.data;
Now find the view code.
page-http.jsp
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8" /> <title> Spring 4 REST + AngularJS </title> </head> <body ng-app="myApp"> <div ng-controller="PersonController"> <h1> Spring 4 REST + AngularJS </h1> <table> <tr><th>ID </th> <th>Name</th> <th>Location</th></tr> <tr ng-repeat="row in persons"> <td><span ng-bind="row.pid"></span></td> <td><span ng-bind="row.name"></span></td> <td><span ng-bind="row.location"></span></td> </tr> </table> </div> <script src="${pageContext.request.contextPath}/app-resources/js/lib/angular.min.js"></script> <script src="${pageContext.request.contextPath}/app-resources/js/app-http.js"></script> </body> </html>
Create Service and Controller
Find the service class and spring controllers used in our example.PersonService.java
package com.concretepage.service; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; import org.springframework.stereotype.Service; import com.concretepage.bean.Person; @Service public class PersonService { private List<Person> list = new ArrayList<>(); { list.add(new Person(1, "Mahesh", "Varanasi")); list.add(new Person(2, "Ram", "Ayodhya")); list.add(new Person(3, "Krishna", "Mathura")); list.add(new Person(4, "Ravan", "Srilanka")); } public Person getPersonById(int pid) { Predicate<Person> personPredicate = p-> p.getPid() == pid; Person obj = list.stream().filter(personPredicate).findFirst().get(); return obj; } public List<Person> getAllPersons(){ return list; } }
package com.concretepage.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import com.concretepage.bean.Person; import com.concretepage.service.PersonService; @RestController @RequestMapping("/info") public class PersonController { @Autowired private PersonService personService; @RequestMapping(value="/person/{id}", method = RequestMethod.GET ) public Person getPersonById(@PathVariable("id") Integer id) { Person person = personService.getPersonById(id); return person; } @ResponseStatus(HttpStatus.OK) @RequestMapping(value= "/person", method = RequestMethod.GET) public List<Person> getAllPersons() { List<Person> list = personService.getAllPersons(); return list; } }
package com.concretepage.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/app") public class HomeController { @RequestMapping("/page-ngresource") public String pageNgResource() { return "page-ngresource"; } @RequestMapping("/page-http") public String pageHttp() { return "page-http"; } }
package com.concretepage.bean; public class Person { private int pid; private String location; private String name; public Person() {} public Person(int pid, String name, String location){ this.pid = pid; this.location = location; this.name = name; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Spring Configuration
Find the java configuration class used in our example.AppConfig.java
package com.concretepage.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration @ComponentScan("com.concretepage") @EnableWebMvc public class AppConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/view/"); resolver.setSuffix(".jsp"); return resolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/app-resources/**").addResourceLocations("/resources/"); } }
Spring Web Application Initializer
Find the web application initializer class.WebAppInitializer.java
package com.concretepage.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[] { AppConfig.class }; } @Override protected Class<?>[] getServletConfigClasses() { return null; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Output
To run demo forngResource
, run the URL
http://localhost:8080/spring4-1/app/page-ngresource
and to run demo for
$http
, run the URL
http://localhost:8080/spring4-1/app/page-http
Find the output for app person.
Spring MVC 4 REST + AngularJS + Hibernate 4 Integration CRUD Tutorial with ngResource Example