Categories: JavaJavascript

AngularJS – How to Get Data from AJAX & Spring MVC


 
The article presents steps one need to code in order to get data from server using XMLHttpRequest (XHR) while working with Spring MVC Java web application. Watch the demo and code samples at http://hello-angularjs.appspot.com/angularjs-http-service-ajax-get-code-example.

Following are key steps:

  1. Write two methods in Spring MVC controller, one to load the page and other to serve AJAX request
  2. Write AngularJS code to get the data (model) in the controller method using $http
  3. Write the view to display the data

 

Spring MVC Controller Methods

Following are two methods one need to write in the Spring MVC Controller:

Method below serves the page, views/httpservice_get.jsp when accessed using the following URL: http://hello-angularjs.appspot.com/angularjs-http-service-ajax-get-code-example. Try and co-relate the request URL mapping and the view (httpservice_get).

@RequestMapping(value = "/angularjs-http-service-ajax-get-code-example", method = RequestMethod.GET)
public ModelAndView httpServiceGetExample( ModelMap model ) {
    return new ModelAndView("httpservice_get");
}

Method below is used to serve the XHR for “/getAllProfiles” URL. Check the Angular $http code for the prior-mentioned URL. Watch out for JSON data in the below that is returned with “@ResponseBody String” return type and annotation.

@RequestMapping(value = "/getAllProfiles", method = RequestMethod.GET)
public @ResponseBody String getAllProfiles( ModelMap model ) {
    String jsonData = "[{\"firstname\":\"ajitesh\",\"lastname\":\"kumar\",\"address\":\"211/20-B,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-888-6666\"},{\"firstname\":\"nidhi\",\"lastname\":\"rai\",\"address\":\"201,mgstreet\",\"city\":\"hyderabad\",\"phone\":\"999-876-5432\"}]";
    return jsonData;
}

 

AngularJS Code with $http Service

The code below demonstrates how to retrieve the data from server using AngularJS $http service based on AJAX GET protocol. It also demonstrates the capability of AngularJS dependency injection which is used to inject $http service to the controller as it is initiated.

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser’s XMLHttpRequest object or via JSONP. The detailed article on $http service could be found on AngularJS $http page.

Pay attention to ‘$http’ service which is injected to the controller. Also notice how data is assigned to $scope.profiles model. AngularJS parses the JSON data for us.

var helloApp = angular.module("helloApp", []);
helloApp.controller("HttpController", [ '$scope', '$http',
function($scope, $http) {
$http({method : 'GET',url : '/getAllProfiles'})
.success(function(data, status, headers, config) {
    $scope.profiles = data;
})
.error(function(data, status, headers, config) {
    alert( "failure");
});
} ])

 

View Displaying JSON Data

Following code displays the JSON data. Pay attention to the usage of ng-repeat directive.

<table class="table">
    <tr>
        <th>Name
        </th>
        <th>Address
        </th>
        <th>City
        </th>
        <th>Phone
        </th>
     </tr>
     <tr ng-repeat="profile in profiles">
         <td>{{profile.firstname + " " + profile.lastname}}
         </td>
         <td>{{profile.address}}
         </td>
         <td>{{profile.city}}
         </td>
         <td>{{profile.phone}}
         </td>
         </tr>
</table>

To summarize, following are the key steps in getting data using AJAX while working with Spring MVC based web application:

  • Write the methods in Spring MVC controller that serves the AJAX request
  • Write the XHR related AngularJS code which calls the controller method using $http service

[adsenseyu1]

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com

Recent Posts

Logistic Regression in Machine Learning: Python Example

Last updated: 26th April, 2024 In this blog post, we will discuss the logistic regression…

23 hours ago

MSE vs RMSE vs MAE vs MAPE vs R-Squared: When to Use?

Last updated: 22nd April, 2024 As data scientists, we navigate a sea of metrics to…

2 days ago

Gradient Descent in Machine Learning: Python Examples

Last updated: 22nd April, 2024 This post will teach you about the gradient descent algorithm…

5 days ago

Loss Function vs Cost Function vs Objective Function: Examples

Last updated: 19th April, 2024 Among the terminologies used in training machine learning models, the…

1 week ago

Model Parallelism vs Data Parallelism: Examples

Last updated: 19th April, 2024 Model parallelism and data parallelism are two strategies used to…

1 week ago

Model Complexity & Overfitting in Machine Learning: How to Reduce

Last updated: 4th April, 2024 In machine learning, model complexity, and overfitting are related in…

2 weeks ago