This example demonstrates the code that is used to post the data to the server using AngularJS $http service based on AJAX POST 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.

Add a Company

Name Employees Head Office
{{company.name}} {{company.employees}} {{company.headoffice}}

Notes

  • Pay attention to inclusion of ngResource as dependent module for assigning custom value to content-type attribute of POST
  • Pay attention to Spring MVC controller method
Include AngularJS resource script file within <head> element
			
<script
	src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.18/angular-resource.js"></script>
			
			
$http Service & Related Code

Pay attention to following:

  • Inclusion of ngResource module
  • Setting the POST content-type; It defaults to application/json. If not set, the AJAX POST would throw 400 error.

			
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';
}]);

$scope.addRow = function(){		
	$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='';
};
			
			
Java Controller Code

Pay attention to saveCompany method which is called from $http service using POST method type.

			
@RequestMapping(value = "/angularjs-http-service-ajax-post-code-example", method = RequestMethod.GET)
public ModelAndView httpServicePostExample( ModelMap model ) {
	return new ModelAndView("httpservice_post");
}
	
@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";
}
			
			
comments powered by Disqus