Spring MVC angularjs example

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
In previous post, we have already seen Spring Restful web services CRUD example. In this post, we will use AngularJS to call Spring MVC CRUD APIs. So we are going to create a view and then perform CRUD operations on the basis of button clicks.
Source code:

click to begin

20KB .zip

Here are steps to create a simple Spring Restful web services which will provide CRUD opertion and angularJS to call Spring MVC APIs.

1) Create a dynamic web project using maven in eclipse named "AngularjsSpringRestExample"

Maven dependencies 

2)Now create pom.xml as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <name>AngularjsSpringRestExample Maven Webapp</name>





Application configuration:

3) create web.xml as below:
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

  <display-name>Archetype Created Web Application</display-name>


create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world examplefor more understanding.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

<context:component-scan base-package="org.arpit.java2blog.controller" />

Create bean class 

5) Create a bean name "Country.java" in org.arpit.java2blog.bean.
package org.arpit.java2blog.bean;

public class Country{
 int id;
 String countryName; 
 long population;
 public Country() {
 public Country(int i, String countryName,long population) {
  this.id = i;
  this.countryName = countryName;
 public int getId() {
  return id;
 public void setId(int id) {
  this.id = id;
 public String getCountryName() {
  return countryName;
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 public long getPopulation() {
  return population;
 public void setPopulation(long population) {
  this.population = population;

Create Controller 

6) Create a controller named "CountryController.java" in package org.arpit.java2blog.controller
package org.arpit.java2blog.controller;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.arpit.java2blog.bean.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

public class CountryController {

 private HttpServletRequest request;
 CountryService countryService = new CountryService();

 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List<Country> getCountries() {
  List<Country> listOfCountries = countryService.getAllCountries();
  return listOfCountries;

 @RequestMapping(value = "/country/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
 public Country getCountryById(@PathVariable int id) {
  return countryService.getCountry(id);

 @RequestMapping(value = "/countries", method = RequestMethod.POST, headers = "Accept=application/json")
 public Country addCountry(@RequestBody Country country) {
  return countryService.addCountry(country);

 @RequestMapping(value = "/countries", method = RequestMethod.PUT, headers = "Accept=application/json")
 public Country updateCountry(@RequestBody Country country) {
  return countryService.updateCountry(country);


 @RequestMapping(value = "/country/{id}", method = RequestMethod.DELETE, headers = "Accept=application/json")
 public void deleteCountry(@PathVariable("id") int id) {


Create Service class

7) Create a class CountryService.java in package org.arpit.java2blog.service
It is just a helper class which should be replaced by database implementation. It is not very well written class, it is just used for demonstration.
package org.arpit.java2blog.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.arpit.java2blog.bean.Country;

 * It is just a helper class which should be replaced by database implementation.
 * It is not very well written class, it is just used for demonstration.
public class CountryService {

 static HashMap<Integer,Country> countryIdMap=getCountryIdMap();

 public CountryService() {

   countryIdMap=new HashMap<Integer,Country>();
  // Creating some objects of Country while initializing
   Country indiaCountry=new Country(1, "India",10000);
   Country chinaCountry=new Country(4, "China",20000);
   Country nepalCountry=new Country(3, "Nepal",8000);
   Country bhutanCountry=new Country(2, "Bhutan",7000);


 public List<Country> getAllCountries()
  List<Country> countries = new ArrayList<Country>(countryIdMap.values());
  return countries;

 public Country getCountry(int id)
  Country country= countryIdMap.get(id);
  return country;
 public Country addCountry(Country country)
  countryIdMap.put(country.getId(), country);
  return country;
 public Country updateCountry(Country country)
   return null;
  countryIdMap.put(country.getId(), country);
  return country;

 public void deleteCountry(int id)

 public static HashMap<Integer, Country> getCountryIdMap() {
  return countryIdMap;

 // Utility method to get max id
 public static int getMaxId()
 {   int max=0;
 for (int id:countryIdMap.keySet()) {  

 return max;

AngularJS view 

8) create angularJSCrudExample.html in WebContent folder with following content:
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
    <title>AngularJS $http Rest example</title>  
 <script type="text/javascript">
            var app = angular.module("CountryManagement", []);
            //Controller Part
            app.controller("CountryController", function($scope, $http) {
                $scope.countries = [];
                $scope.countryForm = {
                    id : -1,
                    countryName : "",
                    population : ""
                //Now load the data from server
                //HTTP POST/PUT methods for add/edit country 
                // with the help of id, we are going to find out whether it is put or post operation
                $scope.submitCountry = function() {
                    var method = "";
                    var url = "";
                    if ($scope.countryForm.id == -1) {
                        //Id is absent in form data, it is create new country operation
                        method = "POST";
                        url = '/AngularjsSpringRestExample/countries';
                    } else {
                        //Id is present in form data, it is edit country operation
                        method = "PUT";
                        url = '/AngularjsSpringRestExample/countries';
                        method : method,
                        url : url,
                        data : angular.toJson($scope.countryForm),
                        headers : {
                            'Content-Type' : 'application/json'
                    }).then( _success, _error );
                //HTTP DELETE- delete country by Id
                $scope.deleteCountry = function(country) {
                        method : 'DELETE',
                        url : '/AngularjsSpringRestExample/country/' + country.id
                    }).then(_success, _error);
             // In case of edit, populate form fields and assign form.id with country id
                $scope.editCountry = function(country) {
                    $scope.countryForm.countryName = country.countryName;
                    $scope.countryForm.population = country.population;
                    $scope.countryForm.id = country.id;
                /* Private Methods */
                //HTTP GET- get all countries collection
                function _refreshCountryData() {
                        method : 'GET',
                        url : 'http://localhost:8080/AngularjsSpringRestExample/countries'
                    }).then(function successCallback(response) {
                        $scope.countries = response.data;
                    }, function errorCallback(response) {
                function _success(response) {
                function _error(response) {
                //Clear the form
                function _clearFormData() {
                    $scope.countryForm.id = -1;
                    $scope.countryForm.countryName = "";
                    $scope.countryForm.population = "";
 background: #25A6E1;
 filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
 padding:3px 5px;
 font-family:'Helvetica Neue',sans-serif;
 border:1px solid #1A87B9

 background: #CD5C5C;

 padding:3px 5px;
 font-family:'Helvetica Neue',sans-serif;
 border:1px solid #CD5C5C

table {
  font-family: "Helvetica Neue", Helvetica, sans-serif;
   width: 50%;

caption {
  text-align: left;
  color: silver;
  font-weight: bold;
  text-transform: uppercase;
  padding: 5px;

th {
  background: SteelBlue;
  color: white;

tbody tr:nth-child(even) {
  background: WhiteSmoke;

tbody tr td:nth-child(2) {

tbody tr td:nth-child(3),
tbody tr td:nth-child(4) {
  text-align: center;
  font-family: monospace;

tfoot {
  background: SeaGreen;
  color: white;
  text-align: right;

tfoot tr th:last-child {
  font-family: monospace;

                border: 1px solid gray;
                width: 25%;
                text-align: left;
                padding: 5px 10px;
    <body ng-app="CountryManagement" ng-controller="CountryController">
           AngularJS Restful web services example using $http
        <form ng-submit="submitCountry()">
                    <th colspan="2">Add/Edit country</th>
                    <td><input type="text" ng-model="countryForm.countryName" /></td>
                    <td><input type="text" ng-model="countryForm.population"  /></td>
                    <td colspan="2"><input type="submit" value="Submit" class="blue-button" /></td>
            <tr ng-repeat="country in countries">
    <td> {{ country.countryName }}</td>
    <td >{{ country.population }}</td>  
                <td><a ng-click="editCountry(country)" class="blue-button">Edit</a> | <a ng-click="deleteCountry(country)" class="red-button">Delete</a></td>

Explanation :

  • We have injected $http as we have done in ajax example through controller constructor.
  • app.controller("CountryController", function($scope, $http) {
                    $scope.countries = [];
  • We have defined various methods depending on operations such as editCountry, deleteCountry, submitCountry
  • When you click on submit button on form, it actually calls POST or PUT depending on operation. If you click on edit and submit data then it will be put operation as it will be update on existing resource. If you directly submit data, then it will be POST operation to create new resource,
  • Every time you submit data, it calls refereshCountryData() to refresh country table below.
  • When you call $http, you need to pass method type and URL, it will call it according, You can either put absolute URL or relative URL with respect to context root of web application.
  •  //HTTP GET- get all countries collection
                    function _refreshCountryData() {
                            method : 'GET',
                            url : 'http://localhost:8080/AngularjsSpringRestExample/rest/countries'
                        }).then(function successCallback(response) {
                            $scope.countries = response.data;
                        }, function errorCallback(response) {

9) It 's time to do maven build.
Right click on project -> Run as -> Maven build

10) Provide goals as clean install (given below) and click on run

Run the application

10) Right click on angularJSCrudExample.html -> run as -> run on server
Select apache tomcat and click on finish

11) You should be able to see below page
URL : "http://localhost:8080/AngularjsJAXRSCRUDExample/angularJSCrudExample.html"

Lets click on delete button corresponding to Nepal and you will see below screen:

Lets add new country France with population 15000

Click on submit and you will see below screen.

Now click on edit button corresponding to India and change population from 10000 to 100000.

Click on submit and you will see below screen:

Lets check Get method for Rest API 

12) Test your get method REST service
URL :"http://localhost:8080/AngularjsSpringRestExample/countries/".
You will get following output:

As you can see , all changes have been reflected in above get call.

Project structure:

Spring MVC angularjs project structure

We are done with Spring Restful web services json CRUD example with angularjs If you are still facing any issue, please comment.

AngularJS tutorial:

    AngularJs hello world example AngularJs controller examples AngularJs ng-repeat example AngularJs Built-in filter example AngularJs custom filter example AngularJs ajax example using $http AngularJS RESTful web service JAXRS CRUD example using $http

If you getting 404 error with above steps, you may need to follow below steps:

1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server: JAXRSJsonCRUDExample' did not find a matching property.

This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove

then remove project from server configuration.
Then run the project under the same server. Warning should be removed now
Or if warning still remains then
  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox. 
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project

This should solve you issues.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012