Home » Enterprise Java » spring » MVC » Spring MVC and Angular 6 Example

About Yatin

Working as a Technical Lead in the Information Technology sector where I'm primarily involved with projects based on Java/J2EE Technologies platform (such as Spring, Spring Boot, Hibernate, Redis, etc.), novel UI technologies (Angular & React), Docker, and AWS. Recently completed the AWS Solution Architect Associate Certification.

Spring MVC and Angular 6 Example

Welcome readers, in this tutorial, we will show the Angular 6 Http Client module and Spring MVC example to fetch the model data. Here, we are using Angular 6 as a front-end technology to make a request and receive the response.

1. Introduction

Refer below diagram to understand the spring mvc and angular 6 applications. The two different applications interact via the HTTP service.

Spring MVC and Angular 6 - Spring Mvc Angular application
Fig. 1: Spring Mvc Angular application

Now, open up the Eclipse IDE and let us see how to implement this tutorial in the spring mvc and angular 6 frameworks.

2. Spring MVC and Angular 6 Example

Here is a systematic guide for implementing this tutorial.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8, Maven, and Angular 6. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring mvc application.

Spring MVC and Angular 6 - Application Structure
Fig. 2: Spring Mvc Application Structure

In addition to this, let us also review the structure of the angular 6 application.

Spring MVC and Angular 6 - Application Structure
Fig. 3: Angular 6 Application Structure

3. Creating Spring MVC application

Below are the steps involved in developing the backend application.

3.1 Maven Dependencies

Here, we specify the dependencies for the Spring and Jackson framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code.


<project xmlns="http://maven.apache.org/POM/4.0.0"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<name>Springmvcangular Maven Webapp</name>
		<!-- Servlet API Dependency -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
		<!-- https://mvnrepository.com/artifact/com.github.javafaker/javafaker -->
		<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->

3.2 Configuration Files

Let us write all the configuration files involved in this application.

3.2.1 Deployment Descriptor

The web.xml file declares one servlet (i.e. Dispatcher Servlet) to receive all kind of the requests. Add the following code to it.


 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

	<display-name>Spring Mvc Angular example</display-name>



3.2.2 Spring Configuration

To configure the mvc framework, developers need to implement the bean configuration file which acts as an interface between the java class and the outside work. Put this file in the Springmvcangular/src/main/webapp/WEB-INF/ folder and add the following code to it.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<context:annotation-config />

	<mvc:annotation-driven />

	<!-- for the stereotype annotation to work -->
		base-package="com.spring.mvc" />

3.3 Java Classes

Let us write all the java classes involved in this application.

3.3.1 Controller class

Add the following code to the employee controller class designed to handle the incoming requests.


package com.spring.mvc.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.spring.mvc.component.Employee;
import com.spring.mvc.service.EmployeeServImpl;

public class EmployeeCtrl {

	EmployeeServImpl empService;

	// Method to test the angular fetch call.
	@CrossOrigin(origins="http://localhost:4200")							// @CrossOrigin is used to handle the request from a difference origin.
	@RequestMapping(value= "/getemployees", method= RequestMethod.GET) 
	public List<Employee> getAllEmployees() {
		return empService.getAllEmployees();

3.3.2 Service class

Add the following code to the employee service class.


package com.spring.mvc.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.spring.mvc.component.Employee;
import com.spring.mvc.repository.EmployeeDaoImpl;

public class EmployeeServImpl {

	EmployeeDaoImpl empdao;

	public List<Employee> getAllEmployees() {
		return empdao.getAllEmployeesFromDb();

3.3.3 Data-Access-Object class

Add the following code to the employee data-access-object class.


package com.spring.mvc.repository;

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

import org.springframework.stereotype.Repository;

import com.github.javafaker.Faker;
import com.spring.mvc.component.Employee;

public class EmployeeDaoImpl {

	// Method to generate the dummy employee records.
	public List<Employee> getAllEmployeesFromDb() {

		// To generate the fake details for the employees.
		Faker faker = new Faker();

		// Employee list.
		List<Employee> employeelist = new ArrayList<Employee>();

		// Creating fake employees to be shown on the angular html page.
		for(int i=101; i<=110; i++) {

			// Creating employee model objects.
			Employee myemployee = new Employee();

			// Adding the employee records to the employee list.

		return employeelist;

3.3.4 Model class

Add the following code to the employee model class.


package com.spring.mvc.component;

import org.springframework.stereotype.Component;

public class Employee {

	private int id;
	private String name;
	private String mobile;
	private String address;
	private String companylogo;

	public int getId() {
		return id;
	public void setId(int id) {
		this.id = id;
	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;
	public String getMobile() {
		return mobile;
	public void setMobile(String mobile) {
		this.mobile = mobile;
	public String getAddress() {
		return address;
	public void setAddress(String address) {
		this.address = address;
	public String getCompanylogo() {
		return companylogo;
	public void setCompanylogo(String companylogo) {
		this.companylogo = companylogo;

4. Creating an Angular 6 application

Run the ng new spring-angular command in the npm console to create a new angular project. Once the new project is created, add the following code to the default module of the angular application.

4.1 Application Module

Add the following code to the app.module.ts file.


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';

  declarations: [
  imports: [
  providers: [],
  bootstrap: [AppComponent]
export class AppModule { }

4.2 Application Component

Add the following code to the app.component.ts file.


import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  title = 'Spring Mvc Angular Tutorial';

  // Object to save the response returned from the service.
  myresponse: any;

  // Url to fetch the employee records from the spring application.
  readonly APP_URL = 'http://localhost:8082/Springmvcangular';

  constructor(private _http: HttpClient) { }

  // Method to fetch all employees from the database table.
  getAllEmployees() {
    this._http.get(this.APP_URL + '/getemployees').subscribe(
      data => {
        this.myresponse = data;
      error => {
        console.log('Error occured', error);

4.3 Application Template

Add the following code to the app.component.html file.



  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

  <div class="container">
    <h1 class="text-danger text-center">Welcome to {{ title }}!</h1>
    <hr />

    <div id="fetchbtn">
      <button type="button" class="btn btn-outline-success" (click)="getAllEmployees();">Click me</button>
    <div><small class="text-info">Click the button to fetch the employees from the database!</small></div>

    <div *ngIf="myresponse">
      <table class="table table-bordered table-hover">
          <th>Employee Id</th>
          <th>Phone no.</th>
          <th>Company Logo</th>
          <tr *ngFor="let employee of myresponse">
            <td><img src="{{employee.companylogo}}" alt="Company logo" class="img-thumbnail mx-auto d-block" style="width: 30%" /></td>


5. Run the Application

As we are ready with all the changes, let us compile the spring project and deploy the application on the Tomcat7 server. In addition, compile and run the angular application with ng serve –o command. Once the projects are successfully compiled and deployed, open the browser to test it.

6. Project Demo

Open your favorite browser and hit the angular application url (http://localhost:4200/) to display the index page of the application.

Spring MVC and Angular 6 - Index Page
Fig. 4: Index Page

Click the button to fetch the employees list from the spring application and display it on the browser.

Spring MVC and Angular 6 - Employees List
Fig. 5: Employees List

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

7. Conclusion

In this section, developers learned how to create a Spring MVC Angular Application. Developers can download the sample application as an Eclipse project in the Downloads section.

8. Download the Eclipse Project

This was a tutorial of Spring MVC and Angular 6 application.

You can download the full source code of this example here: SpringMvcAngular6Example

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area


Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Newest Most Voted
Inline Feedbacks
View all comments
1 year ago

This would only work locally but how would you assign the back end URL that is in the remote server? localhost would not work and would you need to somehow make the IP configurable ?

1 month ago

you could do that using interceptor in angular. prefix the base url or use environment file to configure the base url.