Angular 7 + Spring Boot Login Authentication Example

Angular 7 + Spring Boot Login Authentication Example

In this tutorial we will be creating a Login and Logout page. We will be using a hard coded user name and password for authenticating a user. Also will be implementing session management so that only a used who is logged in can view the pages. Else he will be directed to the login page. In the next tutorial we will be implementing Basic Authentication using Angular 7 and Spring Boot.

In this tutorial we will be creating a Login and Logout page. We will be using a hard coded user name and password for authenticating a user. Also will be implementing session management so that only a used who is logged in can view the pages. Else he will be directed to the login page. In the next tutorial we will be implementing Basic Authentication using Angular 7 and Spring Boot.

In previous tutorial we had implemented - Angular 7 + Spring Boot CRUD Example. We had also created a menu with links to pages.

In this tutorial we will be creating a Login and Logout page. We will be using a hard coded user name and password for authenticating a user. Also will be implementing session management so that only a used who is logged in can view the pages. Else he will be directed to the login page. In the next tutorial we will be implementing Basic Authentication using Angular 7 and Spring Boot.

Angular 7 + Spring Boot CRUD Demo

Angular 7 + Spring Boot Application Hello World Example

Angular 7 + Spring Boot Application CRUD Example

Angular 7 + Spring Boot Application Login Example

Angular 7 development

The angular project we will be developing is as follows-

Create new authentication service

Create a new authentication service where we check if the user name and password is correct then set it in session storage. We will be having the following methods

  • authenticate() Authenticate the username and password
  • isUserLoggedIn() -checks the session storage if user name exists. If it does then return true
  • logout()- This method clears the session storage of user name
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AuthenticationService {

  constructor() { }

  authenticate(username, password) {
    if (username === "javainuse" && password === "password") {
      sessionStorage.setItem('username', username)
      return true;
    } else {
      return false;
    }
  }

  isUserLoggedIn() {
    let user = sessionStorage.getItem('username')
    console.log(!(user === null))
    return !(user === null)
  }

  logOut() {
    sessionStorage.removeItem('username')
  }
}

Create a Login Component

Using the Login Component we will be taking the username and password from the user and passing it to the authentication service to check if the credentials are valid. It will have the following method-

checkLogin()- This method checks if the user credentials are correct by calling the previously created AuthenticationService

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthenticationService } from '../service/authentication.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  username = 'javainuse'
  password = ''
  invalidLogin = false

  constructor(private router: Router,
    private loginservice: AuthenticationService) { }

  ngOnInit() {
  }

  checkLogin() {
    if (this.loginservice.authenticate(this.username, this.password)
    ) {
      this.router.navigate([''])
      this.invalidLogin = false
    } else
      this.invalidLogin = true
  }

}

Modify the LoginComponent html to add the username and password dialogue boxes-

<div class="container">
  <div>
    User Name : <input type="text" name="username" [(ngModel)]="username">
    Password : <input type="password" name="password" [(ngModel)]="password">
  </div>
  <button (click)=checkLogin() class="btn btn-success">
    Login
  </button>
</div>

Add the login path to the routing module.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';
import { LoginComponent } from './login/login.component';

const routes: Routes = [
  { path: '', component: EmployeeComponent },
  { path: 'addemployee', component: AddEmployeeComponent },
  { path: 'login', component: LoginComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Create a Logout Component

In the logout component we clear the session storage username by calling the authentication service.

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../service/authentication.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-logout',
  templateUrl: './logout.component.html',
  styleUrls: ['./logout.component.css']
})
export class LogoutComponent implements OnInit {

  constructor(
    private authentocationService: AuthenticationService,
    private router: Router) {

  }

  ngOnInit() {
    this.authentocationService.logOut();
    this.router.navigate(['login']);
  }

}


Add the logout path to the routing module-

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';

const routes: Routes = [
  { path: '', component: EmployeeComponent },
  { path: 'addemployee', component: AddEmployeeComponent },
  { path: 'login', component: LoginComponent },
  { path: 'logout', component: LogoutComponent },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Modify existing header component to add login , logout menu options

In the component we check if the user is logged in or not. This will be used to decide if all the menu links should be visible to the user or not.

import { Component, OnInit } from '@angular/core';
import { AuthenticationService } from '../service/authentication.service';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {

  isUserLoggedIn:boolean = false;

  constructor(private loginService:AuthenticationService) { }

  ngOnInit() {
    this.isUserLoggedIn=this.loginService.isUserLoggedIn();
    
  }

}

In the header component html we will be adding the login and logout menu. Also we will be showing the menu options to the user only if user is logged in.

 <header>
  <nav class ="navbar navbar-expand-md navbar-dark bg-dark">
  <div><a href="https://www.javainuse.com" class="navbar-brand">JavaInUse</a></div>
  
  <ul class="navbar-nav">
     
    <li><a *ngIf="loginService.isUserLoggedIn()" routerLink="/" class="nav-link">View Employees</a></li>
    <li><a *ngIf="loginService.isUserLoggedIn()" routerLink="/addemployee" class="nav-link">Add New Employee</a></li>
    <li><a *ngIf="!loginService.isUserLoggedIn()" routerLink="/login" class="nav-link">Login</a></li>
    <li><a *ngIf="loginService.isUserLoggedIn()" routerLink="/logout" class="nav-link">LogOut</a></li>
  
  </ul>
    </nav>
  </header>

Now if we go to localhost:4200/login. Login using the credentials -username =‘javainuse’ ,password=‘password’

But what will happen if the user directly tries to access a page without login. For example if a user directly navigates to localhost:4200 He will be able to view the page. But this should not be the case as the user is not logged in. So we should first check if the user is logged in and only then allow the user to view the page. We achive this using the CanActivate interface.

Create the AuthGaurd Service

We will be creating a new Service named AuthGaurdService. This service will activate a particular route only if the user is logged in.

ng generate service service/authGaurd

Let the AuthGaurdService implement the CanActivate interface. By overriding the canActivate method we specify that a route should be active only if the user is logged in.

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthenticationService } from './authentication.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGaurdService implements CanActivate {

  constructor(private router: Router,
    private authService: AuthenticationService) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.authService.isUserLoggedIn())
      return true;

    this.router.navigate(['login']);
    return false;

  }

}

Modify the app.routing.ts to activate route only if the user is logged in using the above AuthGaurdService.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';

const routes: Routes = [
  { path: '', component: EmployeeComponent,canActivate:[AuthGaurdService] },
  { path: 'addemployee', component: AddEmployeeComponent,canActivate:[AuthGaurdService] },
  { path: 'login', component: LoginComponent,canActivate:[AuthGaurdService] },
  { path: 'logout', component: LogoutComponent,canActivate:[AuthGaurdService] },
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Now if the user tries to access a page without logging in, he will be directed to the login page

Download Source Code

Download it -

GITHUB- Angular 7 Login example code

Spring Boot Login example code

Popular Posts

Full Stack Web Development with Angular and Spring MVC

Building Web App using ASP.NET Web API Angular 7 and SQL Server

Angular 7 Tutorial - Learn Angular 7 by Example

Build a Basic App with Spring Boot and JPA using PostgreSQL

Build a Simple CRUD App with Spring Boot and Vue.js

Build a Basic CRUD App with Laravel and Angular

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Build a CRUD App with Angular and Firebase

Angular Authentication Tutorial

Angular 7 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp

How to create a simple web application with Java 8, Spring Boot and Angular

How to create a simple web application with Java 8, Spring Boot and Angular

In this tutorial, we'll look at how developers can combine multiple technologies to make a web application. Read on to get started!

Pre-Requisites for Getting Started
  • Java 8 is installed.
  • Any Java IDE (preferably STS or IntelliJ IDEA).
  • Basic understanding of Java and Spring-based web development and UI development using HTML, CSS, and JavaScript.
Backdrop

In this article, I will try to create a small end-to-end web application using Java 8 and Spring Boot.

I have chosen SpringBoot because it is much easier to configure and plays well with other tech stacks. I have also used a REST API and SpringData JPA with an H2 database.

I used Spring Initializer to add all the dependencies and create a blank working project with all my configurations.

I have used Maven as the build tool, though Gradle can also be used.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>bootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>bootDemo</name>
    <description>Demo project for Spring Boot</description>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
        <relativePath />
        <!-- lookup parent from repository -->
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

In the UI part, I have used AngularJS and BootStrap CSS along with basic JS, CSS, and HTML.

I tried to follow the coding guidelines as much as I could, but all suggestions are welcome.

This is a very simple project which can be useful for creating an end-to-end web application.

Package Structure

Implementation

Let's start with the SpringBootApplication class.

@SpringBootApplication
public class BootDemoApplication {
 @Autowired
 UserRepository userRepository;

 public static void main(String[] args) {
  SpringApplication.run(BootDemoApplication.class, args);
 }
}

Let's create Controllers now. 

@Controller
public class HomeController {
 @RequestMapping("/home")
 public String home() {
  return "index";
 }
}

This will act as the homepage for our SPA. Now we create a Controller to handle some REST calls.

@RequestMapping("/user")
@RestController
public class UserController {
 @Autowired
 UserService userService;

 @RequestMapping(Constants.GET_USER_BY_ID)
 public UserDto getUserById(@PathVariable Integer userId) {
  return userService.getUserById(userId);
 }

 @RequestMapping(Constants.GET_ALL_USERS)
 public List < UserDto > getAllUsers() {
  return userService.getAllUsers();
 }

 @RequestMapping(value = Constants.SAVE_USER, method = RequestMethod.POST)
 public void saveUser(@RequestBody UserDto userDto) {
  userService.saveUser(userDto);
 }
}

Here we have different methods to handle different test calls from the client side.

I have Autowired a Service class, UserService, in the Controller.

public interface UserService {
 UserDto getUserById(Integer userId);
 void saveUser(UserDto userDto);
 List < UserDto > getAllUsers();
}

@Service
public class UserServiceimpl implements UserService {
 @Autowired
 UserRepository userRepository;

 @Override
 public UserDto getUserById(Integer userId) {
  return UserConverter.entityToDto(userRepository.getOne(userId));
 }

 @Override
 public void saveUser(UserDto userDto) {
  userRepository.save(UserConverter.dtoToEntity(userDto));
 }

 @Override
 public List < UserDto > getAllUsers() {
  return userRepository.findAll().stream().map(UserConverter::entityToDto).collect(Collectors.toList());
 }
}

In a typical web application, there are generally two types of data objects: DTO (to communicate through the client) and Entity (to communicate through the DB).

DTO

public class UserDto {
    Integer userId;
    String userName;
    List<SkillDto> skillDtos= new ArrayList<>();
    public UserDto(Integer userId, String userName, List<SkillDto> skillDtos) {
        this.userId = userId;
        this.userName = userName;
        this.skillDtos = skillDtos;
    }
    public UserDto() {
    }
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public List<SkillDto> getSkillDtos() {
        return skillDtos;
    }
    public void setSkillDtos(List<SkillDto> skillDtos) {
        this.skillDtos = skillDtos;
    }
}
public class SkillDto {
    Integer skillId;
    String SkillName;
    public SkillDto(Integer skillId, String skillName) {
        this.skillId = skillId;
        SkillName = skillName;
    }
    public SkillDto() {
    }
    public Integer getSkillId() {
        return skillId;
    }
    public void setSkillId(Integer skillId) {
        this.skillId = skillId;
    }
    public String getSkillName() {
        return SkillName;
    }
    public void setSkillName(String skillName) {
        SkillName = skillName;
    }
}

Entity

@Entity
public class User implements Serializable{
    private static final long serialVersionUID = 0x62A6DA99AABDA8A8L;
@Column
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Integer userId;
    @Column
    private String userName;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<Skill> skills= new LinkedList<>();
    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public List<Skill> getSkills() {
        return skills;
    }
    public void setSkills(List<Skill> skills) {
        this.skills = skills;
    }
    public User() {
    }
    public User(String userName, List<Skill> skills) {
        this.userName = userName;
        this.skills = skills;
    }
}
@Entity
public class Skill {
    @Column
@GeneratedValue(strategy = GenerationType.AUTO)
@Id
private Integer skillId;
    @Column
    private String skillName;
    @ManyToOne
    private User user;
    public Skill(String skillName) {
this.skillName = skillName;
}
public Integer getSkillId() {
        return skillId;
    }
    public void setSkillId(Integer skillId) {
        this.skillId = skillId;
    }
    public String getSkillName() {
        return skillName;
    }
    public void setSkillName(String skillName) {
        this.skillName = skillName;
    }
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    public Skill() {
    }
    public Skill(String skillName, User user) {
        this.skillName = skillName;
        this.user = user;
    }
}

For DB operations, we use SpringData JPA:

@Repository
public interface UserRepository extends JpaRepository<User, Integer>{
}

@Repository
public interface SkillRepository extends JpaRepository<Skill, Integer>{
}

Extending JpaRepository provides a lot of CRUD operations by default, and one can use it to create their own query methods as well. Please read more about this here.

To convert DTO -> Entity and Entity -> DTO, I created some basic converter classes.

public class UserConverter {
 public static User dtoToEntity(UserDto userDto) {
  User user = new User(userDto.getUserName(), null);
  user.setUserId(userDto.getUserId());
  user.setSkills(userDto.getSkillDtos().stream().map(SkillConverter::dtoToEntity).collect(Collectors.toList()));
  return user;
 }

 public static UserDto entityToDto(User user) {
  UserDto userDto = new UserDto(user.getUserId(), user.getUserName(), null);
  userDto.setSkillDtos(user.getSkills().stream().map(SkillConverter::entityToDto).collect(Collectors.toList()));
  return userDto;
 }
}

public class SkillConverter {
 public static Skill dtoToEntity(SkillDto SkillDto) {
  Skill Skill = new Skill(SkillDto.getSkillName(), null);
  Skill.setSkillId(SkillDto.getSkillId());
  return Skill;
 }

 public static SkillDto entityToDto(Skill skill) {
  return new SkillDto(skill.getSkillId(), skill.getSkillName());
 }
}

Let's focus on the UI part now.

While using Angular, there are certain guidelines we need to follow.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="ISO-8859-1">
    <title>Main Page</title>
</head>
<body ng-app="demo">
<hr/>
<div class="container" ng-controller="UserController">
    <div class="row">
        <label>User</label> <input type="text" ng-model="userDto.userName" class="input-sm spacing"/>
        <label>Skills</label> <input type="text" ng-model="skills" ng-list class="input-sm custom-width spacing"
                                     placeholder="use comma to separate skills"/>
        <button ng-click="saveUser()" class="btn btn-sm btn-info">Save User</button>
    </div>
    <hr/>
    <div class="row">
        <p>{{allUsers | json}}</p>
    </div>
    <hr/>
    <div class="row" ng-repeat="user in allUsers">
        <div class="">
            <h3>{{user.userName}}</h3>
            <span ng-repeat="skill in user.skillDtos" class="spacing">{{skill.skillName}}</span>
        </div>
    </div>
</div>
</body>
<script src="js/lib/angular.min.js"></script>
<script src="js/lib/ui-bootstrap-tpls-2.5.0.min.js"></script>
<script src="js/app/app.js"></script>
<script src="js/app/UserController.js"></script>
<script src="js/app/UserService.js"></script>
<link rel="stylesheet" href="css/lib/bootstrap.min.css"/>
<link rel="stylesheet" href="css/app/app.css"/>
</html>

While creating the HTML, don't forget to import the required JS and CSS files.

app.js

'use strict'

var demoApp = angular.module('demo', ['ui.bootstrap', 'demo.controllers',
    'demo.services'
]);
demoApp.constant("CONSTANTS", {
    getUserByIdUrl: "/user/getUser/",
    getAllUsers: "/user/getAllUsers",
    saveUser: "/user/saveUser"
});

UserController.js

'use strict'

var module = angular.module('demo.controllers', []);
module.controller("UserController", ["$scope", "UserService",
    function($scope, UserService) {

        $scope.userDto = {
            userId: null,
            userName: null,
            skillDtos: []
        };
        $scope.skills = [];

        UserService.getUserById(1).then(function(value) {
            console.log(value.data);
        }, function(reason) {
            console.log("error occured");
        }, function(value) {
            console.log("no callback");
        });

        $scope.saveUser = function() {
            $scope.userDto.skillDtos = $scope.skills.map(skill => {
                return {
                    skillId: null,
                    skillName: skill
                };
            });
            UserService.saveUser($scope.userDto).then(function() {
                console.log("works");
                UserService.getAllUsers().then(function(value) {
                    $scope.allUsers = value.data;
                }, function(reason) {
                    console.log("error occured");
                }, function(value) {
                    console.log("no callback");
                });
 
               $scope.skills = [];
                $scope.userDto = {
                    userId: null,
                    userName: null,
                    skillDtos: []
                };
            }, function(reason) {
                console.log("error occured");
            }, function(value) {
                console.log("no callback");
            });
        }
    }
]);


UserService.js

use strict'

angular.module('demo.services', []).factory('UserService', ["$http", "CONSTANTS", function($http, CONSTANTS) {
    var service = {};
    service.getUserById = function(userId) {
        var url = CONSTANTS.getUserByIdUrl + userId;
        return $http.get(url);
    }
    service.getAllUsers = function() {
        return $http.get(CONSTANTS.getAllUsers);
    }
    service.saveUser = function(userDto) {
        return $http.post(CONSTANTS.saveUser, userDto);
    }
    return service;
}]);

app.css

body{
    background-color: #efefef;
}
span.spacing{
    margin-right: 10px;
}
input.custom-width{
    width: 200px;
}
input.spacing{
    margin-right: 5px;
}

The application can be built using:

mvn&nbsp;clean install then run as a runnable jar file by using

java -jar bootdemo-0.0.1-SNAPSHOT.jar or running the main file directly.

Open the browser and hit http://localhost:8080/home

One simple page will open. Enter the name and skills and the entered data will be persisted in the DB.

In the application.properties files, two configurations are to be added.

spring.mvc.view.prefix = /views/
spring.mvc.view.suffix = .html

The source code can be cloned or downloaded from here.

Originally published by Ashish Lohia  at dzone.com

================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Go Full Stack with Spring Boot and Angular

Angular7 CRUD with nodejs and mysql example

Full Stack Web Development with Angular and Spring MVC

Building a Web Application Using Spring Boot, Angular, and Maven

Angular 7 + Spring Boot CRUD Example

Angular 7 + Spring Boot CRUD Example

Angular 7 + Spring Boot CRUD Example

In this tutorial we will be implementing CRUD operations using Angular 7 + Spring Boot.

In this tutorial we will be implementing CRUD operations using Angular 7 + Spring Boot.

In previous tutorial we had implemented - Angular 7 + Spring Boot Hello World Example. We exposed REST endpoint using Spring Boot and consumed this endpoint using Angular 7 application and displayed the data.

In this tutorial we will be implementing CRUD operations using Angular 7 + Spring Boot. We will also be adding the header with menu and footer to our application. So following will be the components on our page.

Angular 7 + Spring Boot CRUD Demo

Angular 7 + Spring Boot Application Hello World Example

Angular 7 + Spring Boot Application CRUD Example

Angular 7 + Spring Boot Application Login Example

The code we had developed in previous application for Angular 7 + Spring Boot Application Hello World Example will be the starting point for this tutorial.

Spring Boot Application

Previous application we had created a simple spring boot application which exposed a REST endpoint for fetching a list of employees. In this tutorial we will be adding 2 more REST endpoints - One for creating an employee and other for deleting it.

package com.javainuse.controllers;

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

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.model.Employee;

@CrossOrigin(origins = "http://localhost:4200")
@RestController
@RequestMapping({ "/employees" })
public class TestController {

	private List<Employee> employees = createList();

	@GetMapping(produces = "application/json")
	public List<Employee> firstPage() {
		return employees;
	}

	@DeleteMapping(path = { "/{id}" })
	public Employee delete(@PathVariable("id") int id) {
		Employee deletedEmp = null;
		for (Employee emp : employees) {
			if (emp.getEmpId().equals(id)) {
				employees.remove(emp);
				deletedEmp = emp;
				break;
			}
		}
		return deletedEmp;
	}

	@PostMapping
	public Employee create(@RequestBody Employee user) {
		employees.add(user);
		System.out.println(employees);
		return user;
	}

	private static List<Employee> createList() {
		List<Employee> tempEmployees = new ArrayList<>();
		Employee emp1 = new Employee();
		emp1.setName("emp1");
		emp1.setDesignation("manager");
		emp1.setEmpId("1");
		emp1.setSalary(3000);

		Employee emp2 = new Employee();
		emp2.setName("emp2");
		emp2.setDesignation("developer");
		emp2.setEmpId("2");
		emp2.setSalary(3000);
		tempEmployees.add(emp1);
		tempEmployees.add(emp2);
		return tempEmployees;
	}

}

Angular 7 development

Modify existing HtppClient Service

We modify the HttpClient service to add methods for performing add new employee and deleting employee in addition to getting the list of employees using the httpClient.

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

export class Employee{
  constructor(
    public empId:string,
    public name:string,
    public designation:string,
    public salary:string,
  ) {}
  
}

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {

  constructor(
    private httpClient:HttpClient
  ) { 
     }

     getEmployees()
  {
    console.log("test call");
    return this.httpClient.get<Employee[]>('http://localhost:8080/employees');
  }

  public deleteEmployee(employee) {
    return this.httpClient.delete<Employee>("http://localhost:8080/employees" + "/"+ employee.empId);
  }

  public createEmployee(employee) {
    return this.httpClient.post<Employee>("http://localhost:8080/employees", employee);
  }
}

Adding BootStrap CSS

In the style.css add the bootstrap css url-

/* You can add global styles to this file, and also import other style files */
@import url(https://unpkg.com/[email protected]/dist/css/bootstrap.min.css)

Modify existing employee component to add delete functionality

In the employee.component.ts file add a call for deleting the employee in addition to getting the list of employees.

import { Component, OnInit } from '@angular/core';
import { HttpClientService, Employee } from '../service/http-client.service';

@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html',
  styleUrls: ['./employee.component.css']
})
export class EmployeeComponent implements OnInit {

  employees: Employee[];
   
  constructor(
    private httpClientService: HttpClientService
  ) { }

  ngOnInit() {
    this.httpClientService.getEmployees().subscribe(
     response =>{this.employees = response;}
    );
  }

  deleteEmployee(employee: Employee): void {
    this.httpClientService.deleteEmployee(employee)
      .subscribe( data => {
        this.employees = this.employees.filter(u => u !== employee);
      })
  };
}

We will be displaying the list of employees in employee.component.html and give users option to delete the employee.

<div class="col-md-6">
  <table class="table table-striped">
  <thead>
  <tr>
    <th>name</th>
    <th>designation</th>
    </tr>
  </thead>
  <tbody>
      <tr *ngFor="let employee of employees">
          <td>{{employee.name}}</td>
          <td>{{employee.designation}}</td>
          <td><button class="btn btn-danger" (click)="deleteEmployee(employee)"> Delete Employee</button></td>
          </tr>
  </tbody>
    </table>

  </div>

Now if we go to localhost:4200

Creating the add employee component

We will be creating a new component named add-employee

ng generate component add-employee

Modify the add-employee.component.ts to make call to spring boot for creating new employee using the httpClientService which is injected in the class using constructor injection.

import { Component, OnInit } from '@angular/core';
import { HttpClientService, Employee } from '../service/http-client.service';

@Component({
  selector: 'app-add-employee',
  templateUrl: './add-employee.component.html',
  styleUrls: ['./add-employee.component.css']
})
export class AddEmployeeComponent implements OnInit {

  user: Employee = new Employee("","","","");

  constructor(
    private httpClientService: HttpClientService
  ) { }

  ngOnInit() {
  }

  createEmployee(): void {
    this.httpClientService.createEmployee(this.user)
        .subscribe( data => {
          alert("Employee created successfully.");
        });

  };

}
	

Modify the add-employee.component.html to create form for getting the new employee details for the employee object to be created.

<div class="col-md-6">
<h2 class="text-center">Add Employee</h2>
<form>
  <div class="form-group">
    <label for="name">Name:</label>
    <input type="name" [(ngModel)]="user.name" placeholder="Name" name="name" class="form-control" id="name">
  </div>

  <div class="form-group">
    <label for="designation">Designation:</label>
    <input [(ngModel)]="user.designation" placeholder="Designation" name="designation" class="form-control" id="designation">
  </div>

  <div class="form-group">
    <label for="empId">Employee Id</label>
    <input [(ngModel)]="user.empId" placeholder="Employee Id" name="Employee Id" class="form-control" id="employeeid">
  </div>

  <button class="btn btn-success" (click)="createEmployee()">Create</button>
</form>
</div>

Since we are using ngModel directive, we will need to add the FormsModule in the app.module.ts- If this is not done you will get an exception as follows - Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’. ("

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

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { EmployeeComponent } from './employee/employee.component';
import { HttpClientModule } from '@angular/common/http';
import { AddEmployeeComponent } from './add-employee/add-employee.component';
import { FormsModule } from '@angular/forms';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeComponent,
    AddEmployeeComponent,
    HeaderComponent,
    FooterComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

In the app.routing.js add the route for this add employee component

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { AddEmployeeComponent } from './add-employee/add-employee.component';

const routes: Routes = [
  { path:'', component: EmployeeComponent},
  { path:'addemployee', component: AddEmployeeComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Go to localhost:8080/addemployee

Creating the header menu

Create new header component-

ng generate component header

Modify the header.component.html to create the menu with links to the view employees and add new employee pages.

  <header>
  <nav class ="navbar navbar-expand-md navbar-dark bg-dark">
  <div><a href="https://www.javainuse.com" class="navbar-brand">JavaInUse</a></div>
  
  <ul class="navbar-nav">
    <li><a  routerLink="/" class="nav-link">View Employees</a></li>
    <li><a  routerLink="/addemployee" class="nav-link">Add New Employee</a></li>
  
  </ul>
  
  </nav>
  
  </header>

Create Footer Component

Create a new component named footer-

ng generate component footer

In the footer specify the data-

<footer class="footer">
  <div class="container">
      <span class="text-muted">All Rights Reserved 2019 @JavaInUse</span>
  </div>

</footer>

Modify the footer.component.css-

    .footer {
    position: absolute;
    bottom: 0;
    width:100%;
    height: 40px;
    background-color: #222222;
}

  • Modify the app.component.html to add the footer and menu to the application byadding the selector tags.
<app-header></app-header>
<router-outlet></router-outlet> 
<app-footer></app-footer>

Go to localhost:4200

Download Source Code

Download it -

GITHUB- Angular 7 CRUD example code

Spring Boot CRUD example code

Popular Posts

Full Stack Web Development with Angular and Spring MVC

Building Web App using ASP.NET Web API Angular 7 and SQL Server

Angular 7 Tutorial - Learn Angular 7 by Example

Build a Basic App with Spring Boot and JPA using PostgreSQL

Build a Simple CRUD App with Spring Boot and Vue.js

Build a Basic CRUD App with Laravel and Angular

AngularJS tutorial for beginners with NodeJS, ExpressJS and MongoDB

MEAN Stack Tutorial MongoDB, ExpressJS, AngularJS and NodeJS

Build a CRUD App with Angular and Firebase

Angular Authentication Tutorial

Angular 7 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

Learn and Understand AngularJS

Angular Crash Course for Busy Developers

The Complete Angular Course: Beginner to Advanced

Angular (Full App) with Angular Material, Angularfire & NgRx

The Web Developer Bootcamp

Building a Web Application Using Spring Boot, Angular, and Maven

Building a Web Application Using Spring Boot, Angular, and Maven

In this article, we will explore the steps used to build a web application using Spring Boot with Angular and Maven and then launch it on a Tomcat Server.

In this article, we will explore the steps used to build a web application using Spring Boot with Angular and Maven and then launch it on a Tomcat Server.

Angular and Spring Boot are both great frameworks which are nowadays in great combination especially by java developers gladly used for building microservices.

In this article I want to show therefore how you can setup a parent maven project which includes an angular and spring boot child, which is finally be deployed on a tomcat server, including production ready jar with some pre-requisties.

Pre-Requisites

Since we are building the project locally and deploy, it’s recommended to try the below mentioned versions and then upgrade or downgrade as per your requirements.

Most importantly, you should also ahve some knowlegde of Spring, Angular, and Maven.

  • Maven version 3.5.2
  • Node version v8.9.3
  • Npm version v5.5.1
  • IntelliJ or any other IDE of your favourite
What Are We Going to Do?

Let’s start building the Spring Boot Project with the following structure.

I have named it AppName — you can specify the any application name youe like.

To begin, it’s recommneded to use https://start.spring.io because its simple and ease to use.

Also, you will need minimum dependencies shown above under the ‘Selected dependencies’ header.

Create Modules for Angular and a Service Module

Once you have downloaded a project and imported it into your favorite IDE, (mine is IntelliJ), right-click on the parent module, i.e AppName, and click ‘New Module’ as shown below.

It’s recommended that you create a module with the project name suffixed with the module name. For example, AppName-UI or AppName-Service.

Once the modules are created, you can see that each module will havea pom.xml file associated with it, as shown in the figure below.

Now its time to discuess what are the modules used for and their purpose.

AppName-Service

This module is used for generating the final depolyment jar which, in turn, has core logic, REST controllers, models, repository classes, etc.

It would also have all the HTML, CSS, and JS files needed for the application.

AppName-UI

This module will contain the Angular project along with the pom.xml

Let’s now examine the pom.xml file used in the project.

The struture of parent pom.xml in the AppName folder of the pom.xml in AppName-Service module are as follows:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>AppName</artifactId>
        <groupId>com.appname.tutorial</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>

    <artifactId>AppName-Service</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Note: You have to remove the build configuration from the Parent pom.xml and place it the AppName-Service’s pom.xml.

Also, it’s important to add packaging in the AppName-Service’s pom.xml.

<packaging>Jar</packaging>

Let’s now look at building the Angular project.

You have to delete the src folder created in the AppName-UI module/folder.

Copy the pom.xml from the AppName-UI module and place it in your Desktop.

Navigate to AppName from the terminal and run the following commands:

cd ~/AppName
rm -rf AppName-UI

Create an Angular 6 Project Using Angular-CLI

Know more about https://cli.angular.io/.

Generate an Angular 6 project using the Angular-CLI from the AppName directory/folder. Navigate to the AppName directoryin the terminal and run the following command:

ng new AppName-UI

Once the above command has been run, you will see that Angular CLI generates a folder/directory including node_modules, package.json, angular-cli.json, etc.

Just to ensure the newly created Angular app runs fine, you can navigate to that folder and run the below command

ng serve

Note:Replace the pom.xml file from the Desktop which we copied in the previous step.

The structure of pom.xml file in the AppName-UI is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>AppName</artifactId>
        <groupId>com.appname.tutorial</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging>

    <artifactId>AppName-UI</artifactId>

    <build>
        <plugins>
            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
                <version>0.0.28</version>
                <configuration>
                    <workingDirectory>./</workingDirectory>
                    <nodeVersion>${node.version}</nodeVersion>
                    <npmVersion>${npm.version}</npmVersion>
                    <nodeDownloadRoot>http://nodejs.org/dist/</nodeDownloadRoot>
                    <npmDownloadRoot>http://registry.npmjs.org/npm/-/</npmDownloadRoot>
                    <installDirectory>./</installDirectory>
                </configuration>
                <executions>
                    <execution>
                        <id>install node and npm</id>
                        <goals>
                            <goal>install-node-and-npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                    </execution>
                    <execution>
                        <id>npm install</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <arguments>ci --loglevel=error</arguments>
                        </configuration>
                    </execution>
                    <execution>
                        <id>npm run-script build-prod</id>
                        <phase>prepare-package</phase>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <configuration>
                            <arguments>run-script build-dev</arguments>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>
</project>


Where Are We Now?

We have created a Spring Boot application running on port 8080. We’ve also created an Angular application running on port 4200.

But we still haven’t achieve our goal of running an Angular application on Spring Boot’s Tomcat Server.

Running an Angular Application on Spring Boot’s Tomcat Server

As you already know, when use ng serve or ng build, Angular CLI generates all the HTML, CSS, andJS files in the dist folder.

Now we need to move that dist folder to AppName-Service’s resources directory.

The easiest way to do that is to open the angular-cli.json file of our Angular application and modify the outDir property as shown below

So, basically, what we are saying is to put all the generated files into the resources of service folder.

Run the Application

Now it’s all yours.

Run mvn clean installfrom the project root directory. This will generate a jar file in the AppName-Service/target directory. It can be deployed to the Tomcat Server and the application can be viewed.

To run the Spring Boot application using Maven, run the following command from the AppName-Servicedirectory.

mvn spring-boot:run

Once the application has started, we should be able to see the index.html in the logs, and open the browser navigate to http://localhost:8080/index.html to see the welcome page.

Angular HTML page accessed via a Tomcat Server.

Complete source code is available on GitHub: https://github.com/ihappyk/AppName

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!