How to integrate Http Angularjs with Spring MVC | Spring Boot

$http is an AngularJS service for communication with remote servers. In the article, JavaSampleApproach will show you way to integrate Http AngularJs and Spring Boot.

Related Articles:
How to configure AngularJs – SpringBoot
How to integrate Angular 4 with SpringBoot Web App and SpringToolSuite
MultipartFile – How to create Spring AngularJs MultipartFile application to download/upload files | SpringBoot + AngularJs + Bootstrap.
AngularJs POST-GET Nested Objects to SpringBoot server
AngularJs POST-GET LIST Objects to SpringBoot server


I. Technologies for Http Angularjs and Spring Boot article

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– AngularJS
– BootStrap

II. Overview
1. Project Structure

http angularjs spring boot - project structure

2. Step to do

– Create SpringBoot project
– Create a simple model
– Create a Controller
– Create a RestController
– Create a index.html page
– Create an angularjs controller with GET & POST methods
– Run & Check result

III. Practices
1. Create SpringBoot project

– Open Spring Tool Suite, on main menu, choose File->New->Spring Starter Project, add project info, then press Next for needed dependencies:
For Template Engines, choose Thymeleaf
For Web MVC, choose Web->Web

angularjs-spring-boot-add-needed-dependencies

Open pom.xml file and check needed dependencies:



	4.0.0

	com.javasampleapproach.angularjs
	angularjs
	0.0.1
	jar

	SpringBootAngularJs
	SpringBoot Angularjs

	
		org.springframework.boot
		spring-boot-starter-parent
		1.4.2.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		

		
			org.springframework.boot
			spring-boot-starter-web
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	




2. Create a simple model

Create a Customer model:

package com.javasampleapproach.angularjs.model;

public class Customer {
	private String firstname;
	private String lastname;
	
	public Customer(){}
	
	public Customer(String firstname, String lastname){
		this.firstname = firstname;
		this.lastname = lastname;
	}
	
	// firstname
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	
	// lastname
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
}
3. Create a Controller

– Create a simple controller for providing an index.html view

package com.javasampleapproach.angularjs.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WebController {
	@RequestMapping(value="/",method = RequestMethod.GET)
    public String homepage(){
        return "index";
    }
}
4. Create a RestController

Create a RestController with 2 RequestMapping:
GET request method that returns all customers.
POST request method that uses for adding a new customer.

package com.javasampleapproach.angularjs.controller;

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

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;

import com.javasampleapproach.angularjs.model.Customer;

@RestController
public class RestWebController {
	
	List cust = new ArrayList();
	
	@RequestMapping(value = "/getallcustomer", method = RequestMethod.GET)
	public List getResource(){
			return cust;
	}
	
	@RequestMapping(value="/postcustomer", method=RequestMethod.POST)
	public String postCustomer(@RequestBody Customer customer){
		cust.add(customer);
		
		return "Sucessful!";
	}
}
5. Create an index.html page

Create a simple index.html page with a form for posting a customer to server, and a button for getting all customers from remote server.

User Bootstrap & Angularjs:





	  Spring Boot - Angularjs Example
	  
	  %MINIFYHTMLb8d9af3c408bd0f4c4c88aca8680034614%%MINIFYHTMLb8d9af3c408bd0f4c4c88aca8680034615%
	  



Http Angularjs With SpringBoot Example

%MINIFYHTMLb8d9af3c408bd0f4c4c88aca8680034616%%MINIFYHTMLb8d9af3c408bd0f4c4c88aca8680034617%

{{postResultMessage}}

  • {{cust.firstname + " " + cust.lastname}}
%MINIFYHTMLb8d9af3c408bd0f4c4c88aca8680034618%
6. Create an angularjs controller with GET & POST methods

Create an angular controller file with 2 methods:
POST method to post a customer’s info to server with url: /postcustomer
$http.post(‘/someUrl’, data, config).then(successCallback, errorCallback);

GET method to get all customers from server with url: /getallcustomer
$http.get(‘/someUrl’, config).then(successCallback, errorCallback);

var app = angular.module('app', []);
app.controller('postcontroller', function($scope, $http, $location) {
	$scope.submitForm = function(){
		var url = $location.absUrl() + "postcustomer";
		
		var config = {
                headers : {
                    'Accept': 'text/plain'
                }
        }
		var data = {
            firstname: $scope.firstname,
            lastname: $scope.lastname
        };
		
		$http.post(url, data, config).then(function (response) {
			$scope.postResultMessage = response.data;
		}, function error(response) {
			$scope.postResultMessage = "Error with status: " +  response.statusText;
		});
		
		$scope.firstname = "";
		$scope.lastname = "";
	}
});

app.controller('getcontroller', function($scope, $http, $location) {
	$scope.getfunction = function(){
		var url = $location.absUrl() + "getallcustomer";
		
		$http.get(url).then(function (response) {
			$scope.response = response.data
		}, function error(response) {
			$scope.postResultMessage = "Error with status: " +  response.statusText;
		});
	}
});
7. Run & Check result

Run Spring Boot Application and check result:
http angularjs spring boot result

IV. Sourcecode

SpringBootAngularJS



By grokonez | December 28, 2016.

Last updated on November 8, 2017.



Related Posts


20 thoughts on “How to integrate Http Angularjs with Spring MVC | Spring Boot”

    1. Hi,

      You can do an http DELETE via an URL /customer/delete/{id} and AngularJs’s $http.delete function.

      In the Spring’s Controller, You need implement a new request mapping with annotation @DeleteMapping:

      @DeleteMapping("/customer/delete/{id}")
      public String deleteMethod(@PathVariable int id) {
      	// to do
      	return "OK";
      }
      

      Regards,

      1. Thank you!
        Although I still have some problems, could you help me out?
        I think something is still wrong with passing the path variable, i keep getting deleteResultMessage=”Failed”
        Here is my code:

        HTML:

               
                    Which client do you want to delete? (id)
                    
                    Remove
                    {{deleteResultMessage}}
                
        

        CONTROLLER.JS

        app.controller('deleteController', function($scope, $http, $location) {
            $scope.submitForm = function(){
                var config = {
                    headers : {
                        'Content-Type': 'application/json;charset=utf-8;'}}
                var data = {
                    id: $scope.id
                };
        
                var url = $location.absUrl() + "delete" + id;
        
                $http.delete(url, data, config).then(function (response) {
                    $scope.deleteResultMessage = "Success";
                }, function (response) {
                    $scope.deleteResultMessage = "Failed";
                });
                $scope.id = null;
            }
        });
        

        and RestWebCotroller:

        @DeleteMapping("/delete/{id}")
            public String delete(@PathVariable Long id) {
                clientService.delete(id);
                return "OK";
            }
        
          1. Ahhhhh, once i post the comment =my html code changes. Last attempt, of course in the programm i have “”:

            div ng-controller="deleteController"
                    form   name="clientForm" ng-submit="submitForm()"
                       label   Which client do you want to delete? (id)      /label
                       input     type="number" name="id" class="form-control" ng-model="id"   
                       button    type="submit" class="btn btn-danger custom-width"Remove   /button
                       p   {{deleteResultMessage}}   /p
                   /form>
            
            
          2. Hi,

            1. Firstly, please check again your url request:
            -> Your URL: var url = $location.absUrl() + "delete" + id;
            Correct is: var url = $location.absUrl() + "delete/" + id;

            2. Second:

            Default AngularJS with headers: 'Accept': 'application/json'
            Your controller returns a String format.

            -> Your’s Problem

            Solution:

            var config = {
                            headers : {
                                'Accept': 'text/plain'
                            }
                    }
            		
            $http.delete(url, config)
            
    1. Hi,

      You can open a Eclipse Terminal by right click on the project -> Show in Local Terminal -> Terminal or Ctrl + Alt + T

      Then use the command-lines to build and run Spring Boot project: {mvn clean install, mvn spring-boot:run}

  1. Hi, should you please show us how to do the remember-me functionnality from angular js to spring boot? Thanks in advance.

      1. ok thanks really. Really it is a wonderfull article.I try to do it but i don’t succeded and my problem in angular js how to pass parameters from js to spring boot security.

  2. Hi,

    I also try to implement the remember-me feature with angular js and spring boot but i didn’t succeded: this is the first part of my back end my SecurityConfigWeb.java:

    http.authorizeRequests()
            .antMatchers("/sentEmail", "/contactUs", "/reset", Constants.PATTERN1,Constants.PATHPATTERN2, Constants.PATHPATTERN3).permitAll()
            .anyRequest().authenticated().and()
            	.formLogin()
                .loginPage(Constants.URL_PATH)            
                .successHandler(this.authSuccess)
                .failureHandler(this.authFailure).permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(this.logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll()
                .and().rememberMe().key("myAppKey").rememberMeServices(rememberMeServices())
                .and()
                .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
    

    but for the front end angular js: this is my login.jsp
    Stay Logged In

    but for the loginservice.js and loginController.js i don’t succeded.

    Really, i need it please could you help me ?
    Thanks in advance.

    1. Hello Vincent,

      You can follow the guide steps as below:

      1. Create AngularJs Controller for login, logout functions:

      // Config XMLHttpRequest to avoid pop-up alert with the default header 'WWW-Authenticate: Basic'.
      app.config([ '$httpProvider', function($httpProvider) {
      	$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
      } ]);
      
      // Controller
      app.controller('AppCtrl', function($http, $scope) {
      	
      	// login function
      	$scope.login = function() {
      		// base64 encoded from username & password
      		var base64Credential = btoa($scope.username + ':' + $scope.password);
      		
      		// GET request for user details
      		$http.get('user', {
      			headers : {
      				// Authorization Header
      				'Authorization' : 'Basic ' + base64Credential
      			}
      		}).success(function(result) {
      			if (result.authenticated) {
      				$scope.msg = '';
      				$scope.userDetails = result;
      			} else {
      				$scope.msg = 'Authetication Failed !';
      			}
      			$scope.password = null;
      		}).error(function(error) {
      			$scope.msg = 'Authetication Failed !';
      		});
      	};
      	
      	// logout 
      	$scope.logout = function() {
      		// clear authorization header
      		$http.defaults.headers.common['Authorization'] = null;
      		// clear data
      		$scope.userDetails = null;
      		$scope.msg = 'Successfully logged out';
      	};
      	
      	$scope.logout = function() {
      	  $http.post('logout', {}).success(function() {
      		$scope.userDetails = null;
      		$location.path("/");
      	  }).error(function(data) {
      		$scope.userDetails;
      	  });
      	}
      

      2. Create a GET RestAPI for userInfo

      	
      	@RequestMapping("/user")
      	public Principal sayHello(Principal principal) {
      		return principal;
      	}
      

      Regards,
      JSA

      1. I do that this is my loginController:

        function loginController($scope,toastr, loginService,UsersService, $state,$http) {
        	/*
        	 * 
        	 * login user after verifying the login service
        	 * */
        	 $scope.loginerror = false ;
        	$scope.n=0;
        	$scope.login = function() {
        		$scope.n=$scope.n;
        		loginService.login($scope.account).then(function(data) {	
        		
        			$scope.uiRouterState = $state;
        			
        			$state.go("dashboard");
        		}, function(data) {
        
        		
        		  //  $scope.loginerror = function(data) {
        			$scope.error = data.data["AuthenticationErrorMessage"];
        			
        			$scope.n=$scope.n+1;
        			console.log("n: ", $scope.n);
        		});
        
        	};
        
        and my loginService.js:
        
        function loginService($http, $base64, $state) {
        	var session = {};
        	session.login = function(data) {
        		return $http.post(_contextPath + '/',
        				"username=" + data.username + "&password=" + data.password, {
        					headers : {
        						'Content-Type' : 'application/x-www-form-urlencoded'
        					}
        				}).success(function(response) {
        			return response.status;
        		}).error(function(response) {
        			return response.status;
        		})
        	};
        
        	session.logout = function() {
        		$http.post(_contextPath + '/logout', {}).success(function(data) {
        			$state.go("login");
        		}).error(function(data) {
        			alert("error" + data);
        		});
        	}
        
        	session.getUser = function() {
        		$http.get(_contextPath + "/getUser").success(function(data) {
        			if (data.userLogin) {
        				session.User = data.userLogin;	
        			}else{
        				$state.go("login");
        			}
        		}).error(function() {
        		});
        	}
        
        	return session;
        };
        

        This is my login.jsp for remember-me:
        Stay Logged In, my problem is my remember-me feature , i don’t succeeded to do it ,could you help me

        Thanks.

  3. Hi, I’m new in AngularJS and Spring. Can you help me to understand why I get customer null in postcustomer method?
    I tried to change the method input to String:

    @RequestMapping(value=”/postcustomer”, method=RequestMethod.POST)
    public String postCustomer(@RequestBody String customer){
    System.out.println(customer);
    //cust.add(customer);

    return “Sucessful!”;
    }

    and the output is correct:

    {“firstname”:”dfgdg”,”lastname”:”dfdfg”}

    What is going wrong?

  4. Hello

    I was bit confuse how to update any entries onclick of Edit function , Please someone help
    I am using this mapping for update in restcontroller

    @ResponseBody
    @PutMapping(“/update/{id}”)
    public update updateCust(@PathVariable(value = “id”) Long Id) {

    Customer cust = repository.findById(Id);

    cust.setfirstName(cust.getfirstName());
    cust.setlastName(cust.getlastName());

    Note updatedNote = repository.save(cust);
    return updatedNote;
    }

  5. how do i format the {{postResultMessage}}
    If my message is “success !! Thanks for using!!!”
    and If I insert line breaks like “success!! Thanks for using!!!”

    The page displays “success!! Thanks for using!!!” it does not honor tags.

Got Something To Say:

Your email address will not be published. Required fields are marked *

*