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.employees}} {{company.headoffice}}


  • 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
$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) {    
	$['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

$scope.addRow = function(){		
	$scope.companies.push({ 'name':$, 'employees': $scope.employees, 'headoffice':$scope.headoffice });
	// Writing it to the server
	var data = 'name=' + $ + '&employees=' + $scope.employees + '&headoffice=' + $scope.headoffice;								
	$'/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
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