Jul 7, 2016

How to integrate AngularJS with Java spring framework?
Share

Written by : Johnny Morgan| 12 | Programming

Professionals of java development India will explain the concept of AngularJS and will share integration method of AngularJS with Java Spring framework. You can read this post further and learn the steps.

Introduction

AngularJS is robust client side scripting framework. It is developed on top of Java script.  Using AngularJS we can directly bind the html components to application server side variables. We can integrate AngularJS to any server side program. This article covers how to integrate AngularJS with Spring Framework. The traditional java scripting code is not maintainable, but AngularJS provides MVC design pattern. It separates the view, data and request/response which called as MVC. Separation gives the better code maintainability. The Model represents the AngularJS Data Model which holds the server side objects. View is having AngularJS Directives which used to bind the data from Model Layer. The Controller is actual AngularJS code which handling data communication between Model and View.

Java Anguilar Spring

Prior to start Angular JS with Spring Framework, you should understand about following AngularJS component.

  • ng-app
  • ng-model
  • ng-bind
  • ng-controller

ng-app

The ng – app denotes the starting point of Angular JS in your application.

ng-model

The ng-model binds the Angular data in input component.

ng-bind

The ng-bind is to display the angular data to HTML component.

ng-controller

The ng-controller is a middle component between AngularJS data and html component. It helps to data communication between AngularJS data and html component.

The above all component called as AngularJS directives.

The below simple example shows that how to use aboveAnguarJS directives.

<html>

<head>

<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>

</head>

            <title>Angular JS with Spring framework</title>

            <body ng-app="myApp">

            <div ng-controller="studentController">

            <h2 align="center" ng-bind="student.title"></h2>

            <div style="text-align:center">

<p>Enter First Name: <input type="text" ng-model="student.firstName"></p>       <p>Enter Last Name: <input type="text" ng-model="student.lastName"></p>

</div>

<div style="margin-left:500px;">

<p>You have entered value is {{student.fullName() | uppercase}}</p>

</div>

</div>

</body>

</html>

<script>

            varmyapp = angular.module("myApp",[]);   

            //angular.module("myApp",[])

            myapp.controller('studentController', function($scope) {

                        $scope.student = {

                                                title:"Angular JS with Spring framework",

                                                firstName: "",

                                                lastName: "",

                                                fullName: function() {

                                                            varstudentObject;

                                                            studentObject = $scope.student;

                                                            returnstudentObject.firstName + " " + studentObject.lastName;

                                                }

                        };

            });

</script>  

<body ng-app="myApp">

In the above example body tag is having ng-app=myApp parameter which says that starting point of your AngularJS. All AngularJS related directives should come inside the ng-app.

<div ng-controller="studentController">

In the above tag uses the ng-controller parameter which says that the div tag act as a controller section where all data binding happens from AngularJS script. We can bind AngularJS data with the html component which are enclosed with studentController section. We walk through the AngularJS Script before going into html component in the studentController.

varmyapp = angular.module("myApp",[]);

This Angular code initiates the Angular application. Whatever html section available in myApp those are inside the scope of AngularJS.

myapp.controller('studentController', function($scope) {

myapp.controller creates a new controller in which we can create many variable using $scope variable. $scope is a predefined AngularJS variable.Based on above example $scope variable initiates the student object in which following three properties and method is created.

title,firstName,lastName and fullName()

Now my objective is bind all above variable in the html component which are enclosed in studentController. Following is the right way to creating object under $scope variable

$scope.student = {

title:"Angular JS with Spring framework",

            firstName: "",

            lastName: "",

            fullName: function() {

                        varstudentObject;

                        studentObject = $scope.student;

                        returnstudentObject.firstName + " " + studentObject.lastName;

            }

}
<h2 align="center" ng-bind="student.title"></h2>

The above h2 tag binds with student.title value. AngularJS send the title value to h2 Tag.

<p>Enter First Name: <input type="text" ng-model="student.firstName"></p>

<p>Enter Last Name: <input type="text" ng-model="student.lastName"></p>

firstName and lastName binds with input boxes. Whatever value user types in the input boxthose values assigned to firstName and lastName.

<p>You have entered value is {{student.fullName() | uppercase}}</p>

The paragraph tag binds with fullName() method. This method concatenates the firstName and lastName then, returns fullName to paragraph tag. Uppercase is a predefine function which converts to uppercase. Below is the screenshot for above example.

1

The above AngularJS example is not integrated with Spring Framework but it gives a better understanding about the AngularJS. The next example demonstrates how to integrate above example in Spring Framework.

Create Maven based spring web application. Following is the folder structure I have created.Make sure everything you have as is in the screenshot.

2

I assumed that the reader of this article already knows the spring framework so, this article concentrating on AngularJS integration perspective. Download 1.2.29 AngularJS from the following link.

https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js

Once pasted above URLin the browser, you will get angular JS entire script code in the browser as in the screenshot below.

3

Select above content and save in a .js file.Name it as “angular.min.js”

Add following maven dependency in pom.xml file

<dependency>

<groupId>com.google.code.gson</groupId>

<artifactId>gson</artifactId>

<version>2.7</version>

</dependency>

This dependency required to convert Java server response to JSON response.

Create a JS file under webapp/js/1.2.29/ file and name the file as “angularcontroller.js”. This file should have an AngularJS controller script. This AngularJS script connects with Java Spring controller class for retrieving the response data from Java script controller class.

Following is AngularJS controller code.

var app = angular.module('myApp', []);

functionstudentController($scope, $http) {




$scope.getDataFromServer = function() {

        $http({

method : 'GET',

url : 'getstudentdata' // invoking spring method

                }).success(function(data, status, headers, config) {

                        $scope.student = data;

                }).error(function(data, status, headers, config) {

          });

    };

};

According to the above code, the AngularJS Controller name is student Controller.This controller is having a method called getData From Server. This method invokes the spring method getStudentData via getstudentdatarequest mapping which referred in studne tController scripting code.

@RequestMapping(value ="/getstudentdata", produces={"application/xml", "application/json"})

public @ResponseBody String getStudentData(HttpServletRequestrequest,HttpServletResponse response) {

HashMap<String, String>studentMap = new HashMap<String,String>();

studentMap.put("title", "AngularJS with Spring framework");

studentMap.put("firstName","Suresh");

studentMap.put("lastName","Stalin");

        String jsonResponse = new Gson().toJson(studentMap);

            returnjsonResponse;

}

The above method returns JSON response data. Based on above example JSON response should have “firstName, lastName and title”.

The above code populates those data in Hashmap. UsingGson API converting Hashmap data to JSON response data.

Following code is view section of AngularJS. It holds the AngularJS variable using its AngularJS directives.

<div ng-controller="studentController">

<h2 align="center" ng-bind="student.title"></h2>

<div>

<button ng-click="getDataFromServer()">Fetch data from server</button>

<p>First Name : {{student.firstName}}</p>

<p>Last Name : {{student.lastName}}</p>

</div>

</div>

Following code is Controller section of angularJS. This section invokes when clicks the button. This controller connects to spring controller and fetches the data and populates in AngularJS object variable (student) which is called as a Model.Now hopefully, you understand how MVC is playing in AngularJS.

$scope.getDataFromServer = function() {

        $http({

method : 'GET',

url : 'getstudentdata'

                }).success(function(data, status, headers, config) {

                        $scope.student = data;

                }).error(function(data, status, headers, config) {

          });

    };




<h2 align="center" ng-bind="student.title"></h2>

<p>First Name : {{student.firstName}}</p>

<p>Last Name : {{student.lastName}}</p>

The title , firstName and lastName populates in above html tag.

Make sure you have to include the following script files

<script src = "${pageContext.request.contextPath}/js/1.2.29/angular.min.js"></script>

<script type="text/javascript" src="${pageContext.request.contextPath}/js/angularcontroller.js"></script>

AngularJS System diagram based on our example

4

All the coding shared in this post is designed by java development India experts to help community people and make them learn about the process of integrating AngularJS with Spring framework. If there are doubts, ask directly to the experts.

Save

Save

Tags: ,

Johnny Morgan

Johnny Morgan

Technical Writer at Aegis Infoways
Johnny Morgan as a technical writer at Aegis Infoways since more than 6 years. I write articles especially for Java, Python and Asp.Net. I have also got well response to write articles on CRM, Hadoop and QA.You can contact me on Twitter, Reddit and G+.
Johnny Morgan
12
Opt In Image
Write An Article For Us?
Attention: Accepting Guest Post Submissions!

Do you have a small, medium or large company looking to reach a new audience for your content? We are currently working with new contributors as authors and curators. Please read our submission guidelines. Learn how to benefit from partnering with us.

 


Content Curator

Johnny Morgan

Johnny Morgan as a technical writer at Aegis Infoways since more than 6 years. I write articles especially for Java, Python and Asp.Net. I have also got well response to write articles on CRM, Hadoop and QA.You can contact me on Twitter, Reddit and G+.

More Curations by Johnny