AngularJS – How to Post JSON Data using AJAX & SpringMVC

0


 
The article presents code samples that one could use to quickly get started with posting JSON data using AngularJS  $http service while working with SpringMVC web application. The demo for the code below could be found on this page, http://hello-angularjs.appspot.com/angularjs-http-service-ajax-post-json-data-code-example.  Earlier, I posted this article where one could post the html data (text/html) using AJAX & SpringMVC.

Following are key steps:

  • Create SpringMVC Controller methods and a POJO
  • Create AngularJS Controller Method
  • Create View

 

SpringMVC Controller methods and a POJO

Following are key steps:

  • Create a controller method to access the page consisting of UI that will be posting using AJAX
    @RequestMapping(value = "/angularjs-http-service-ajax-post-json-data-code-example", method = RequestMethod.GET)
    public ModelAndView httpServicePostJSONDataExample( ModelMap model ) {
    	return new ModelAndView("httpservice_post_json");
    }
  • Create a controller method that shall be receiving the JSON data posted by $http service using XHR (AJAX)
    @RequestMapping(value = "/savecompany_json", method = RequestMethod.POST)	
    public  @ResponseBody String saveCompany_JSON( @RequestBody Company company )   {		
    	//
    	// Code processing the input parameters
    	//	
    	return "JSON: The company name: " + company.getName() + ", Employees count: " + company.getEmployees() + ", Headoffice: " + company.getHeadoffice();
    }
  • Create a POJO which maps to JSON object
    package com.vitalflux.core;
     
    public class Company {
     
    	private String name;
    	private long employees;
    	private String headoffice;
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public Long getEmployees() {
    		return employees;
    	}
    	public void setEmployees(Long employees) {
    		this.employees = employees;
    	}
    	public String getHeadoffice() {
    		return headoffice;
    	}
    	public void setHeadoffice(String headoffice) {
    		this.headoffice = headoffice;
    	}
    }
  • Include Jackson library. This is one of the MOST IMPORTANT STEP. I recommend to read this article on how to fix 415 Unsupported Mediatype error which one may hit if he forgets to implement this step. This is one error that may haunt most of the newbies.

 

Create AngularJS Controller Method

Following code could be used to post JSON data  to the server. Following assumes that you shall be creating the ng-app with name as “helloAjaxApp”.

 

var helloAjaxApp = angular.module("helloAjaxApp", []);
 
helloAjaxApp.controller("CompaniesCtrl", ['$scope', '$http', function($scope, $http) {
	$scope.companies = [
	                    { 'name':'Infosys Technologies',
	                    	'employees': 125000,
	                    	'headoffice': 'Bangalore'},
	                    	{ 'name':'Cognizant Technologies',
		                    	'employees': 100000,
		                    	'headoffice': 'Bangalore'},
		                    	{ 'name':'Wipro',
			                    	'employees': 115000,
			                    	'headoffice': 'Bangalore'},
			                    	{ 'name':'Tata Consultancy Services (TCS)',
				                    	'employees': 150000,
				                    	'headoffice': 'Bangalore'},				                    	
	                    ];
 
	$scope.addRowAsyncAsJSON = function(){		
		$scope.companies.push({ 'name':$scope.name, 'employees': $scope.employees, 'headoffice':$scope.headoffice });
		// Writing it to the server
		//		
		var dataObj = {
				name : $scope.name,
				employees : $scope.employees,
				headoffice : $scope.headoffice
		};	
		var res = $http.post('/savecompany_json', dataObj);
		res.success(function(data, status, headers, config) {
			$scope.message = data;
		});
		res.error(function(data, status, headers, config) {
			alert( "failure message: " + JSON.stringify({data: data}));
		});		
		// Making the fields empty
		//
		$scope.name='';
		$scope.employees='';
		$scope.headoffice='';
	};
}]);

 

Create View

Following is the view code that represents the call to the method, addRowAsyncAsJSON, to post the JSON data:

<form class="form-horizontal" role="form" ng-submit="addRowAsyncAsJSON()">
	<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>

[adsenseyu1]

Ajitesh Kumar

Ajitesh is passionate about various different technologies including programming languages such as Java/JEE, Javascript, PHP, .NET, C/C++, mobile programming languages etc and, computing fundamentals such as application security, cloud computing, API, mobile apps, google glass, big data etc.

Follow him on Twitter and Google+.
Share.

Leave A Reply


eight − = 1