AngularJS – How to POST Data using AJAX & Spring MVC – Part 1

4

The article presents the code example that one may use to post data to server using AngularJS $http service, while working with Spring MVC web application. The same is demonstrated in the following page: http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-code-example. This article is first in the series of articles on different techniques that could be used to POST different formats of data to the server when working with AngularJS and Spring MVC. In this article, the code samples demonstrate how to post plain HTML text data (text/html) format to the server.

Following are key steps:

  • Create Spring MVC web controllers methods
  • Create AngularJS controller method using $http service to post data
  • Create view to receive input data

Spring MVC Controller Methods

Following are different controller methods that will be required for first, accessing the page and then, posting the data using AJAX.

The code below is used to access the main web page from where AJAX request will be posted.
@RequestMapping(value = "/angularjs-http-service-ajax-post-code-example", method = RequestMethod.GET)
public ModelAndView httpServicePostExample( ModelMap model ) {
	return new ModelAndView("httpservice_post");
}
The code below is used to receive request parameters in html-text format (text/html) when posted using AJAX.
@RequestMapping(value = "/savecompany", method = RequestMethod.POST)
public  @ResponseBody String saveCompany( @RequestParam("name") String name,
		@RequestParam("employees") long employees,
		@RequestParam("headoffice") String headoffice) {		
	//
	// Code processing the input parameters
	//		
	return "The company data (name: " + name + ", employees: "+ String.valueOf( employees ) + ", headoffice: " + headoffice + ") is saved";
}

AngularJS Controller Method using $http Service

Following are set of code that needs to be written to post the AJAX request data in plain text format (text/plain). Before going over the code, pay attention to following:

  • The data is posted in the format, n1=v1&n2=v2&n3=v3. Posting this data without the code explained in next step throws an error. This is because “Content-Type” for $http.post defaults to ‘application/json’, while we are trying to send the data in plain text, name-value, traditional format. Check this link for detail, https://docs.angularjs.org/api/ng/service/$http.
  • Define a global configuration and set the ‘Content-Type’ of POST method to something such as following that demonstrated in following code. Pay attention to the fact that you would be required to include angular-resource.js script for working with ngResource dependency.
    var helloApp = angular.module("helloApp", ['ngResource']);
    
    helloApp.config(['$httpProvider', function ($httpProvider) {    
    	$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    }]);
  • Define the $http code to post the data to server in the way sich as that shown below.
    $scope.addRowAsync = function(){
    // Add the data to the model
    //
    $scope.companies.push({ 'name':$scope.name, 'employees': $scope.employees, 'headoffice':$scope.headoffice });
    // Writing it to the server
    //
    var data = 'name=' + $scope.name + '&employees=' + $scope.employees + '&headoffice=' + $scope.headoffice;
    $http.post('/savecompany', data )
    .success(function(data, status, headers, config) {
    $scope.message = data;
    })
    .error(function(data, status, headers, config) {
    alert( "failure message: " + JSON.stringify({data: data}));
    });
    // Making the fields empty
    //
    $scope.name='';
    $scope.employees='';
    $scope.headoffice='';
    };

View to Receive Input Data

Following code represents view from where data is entered and submitted. Pay attention to ng-submit directive.

<form class="form-horizontal" role="form" ng-submit="addRowAsync()">
     <div class="form-group">
        <label class="col-md-2 control-label">Name</label>
            <div class="col-md-4">
                 <input type="text" class="form-control" name="name"
                  ng-model="name" />
            </div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">Employees</label>
            <div class="col-md-4">
                <input type="text" class="form-control" name="employees"
                 ng-model="employees" />
            </div>
    </div>
     <div class="form-group">
          <label class="col-md-2 control-label">Headoffice</label>
             <div class="col-md-4">
                 <input type="text" class="form-control" name="headoffice"
                  ng-model="headoffice" />
             </div>
     </div>
     <div class="form-group">
           <div style="padding-left:110px">
              <input type="submit" value="Submit" class="btn btn-primary"/>
           </div>
     </div>
</form>



Ajitesh Kumar

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, C/C++, mobile programming languages etc, and, computing fundamentals related with cloud-native technologies, application security, cloud computing platforms, mobile apps, big data etc.

He has also authored the book, Building Web Apps with Spring 5 and Angular.
Ajitesh Kumar

4 Comments

  1. Pingback: AngularJS - How to Post JSON Data using AJAX & SpringMVC - Bytes Cravings

    • Hi..
      I am facing problem while downloading a file..
      I am able to do that, if sending simple parameters with url
      like <a href="\\username=123>download

      but when i am trying to send JSON object, its not working, terminating to some unknown URL.

      when I am sending it like
      $http .post(‘rest/?cd=$scope.OpmMainPageDTO)
      .success(function(data){} )
      .error()

      I am able to send JSON data on server and receive the data back in success, but that file is not downloading on client.

      Please help how to download the file from ModelandView response.

  2. I suppose the SpringController method which you are calling returns a string, which obviously specifies your home page, as a part of refresh.

    This will supress the file from getting downloaded due to the “org.springframework.web.servlet.view.InternalResourceViewResolver” which you would have specified in your applicationContext.

    This appends your file-to-be-download to a jsp file, thereby not getting downloaded.

    Solution:
    Remove the string return type and change as void. Do not return a string.

    Hope it helps!

Leave A Reply

Time limit is exhausted. Please reload the CAPTCHA.