Search Tutorials


Ecommerce Website - Online Book Store - Create User Admin Module - Part 1 | JavaInUse
     
 

   
   

Ecommerce Website - Online Book Store - Create User Admin Module - Part 1

In this tutorial series we will be developing an ecommerce website for buying books. In a previous tutorial created an angular 8 project and added menu component.
Next we will be creating the User Admin Module. Using this we will be able to add new users, list/display user details and delete existing users. In this tutorial we will creating the component named Users Component using which we can list the existing users. This user list will be fetched from mysql db using Spring Boot.

Ecommerce Website - Online Book Store using Angular 8 + Spring Boot

Ecommerce Website - Online Book Store using Angular 8 + Spring Boot Introduction Ecommerce Website - Online Book Store - Create Menu Module Ecommerce Website - Online Book Store - Create User Admin Module - Part 1 Ecommerce Website - Online Book Store - Create User Admin Module - Part 2 Ecommerce Website - Online Book Store - Create User Admin Module - Part 3 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 1 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 2 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 3 Ecommerce Website - Online Book Store - Create Book Admin Module - Part 4 Ecommerce Website - Online Book Store - Create Book Shopping Module

Video

This tutorial is explained in the below Youtube Video.

Spring Boot Application

We will be creating a simple Spring Boot Application to expose a REST end point to return a list of users. For this tutorial we will make use of JPA Repository to perform mysql operations.
Maven Project will be as follows-

The pom.xml will be 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/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javainuse</groupId>
	<artifactId>spring-boot-ecommerce</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.1.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-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>

	</dependencies>
</project>



Create the EcommerceApplication.java with the SpringBootApplication annotation as below-
package com.javainuse;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EcommerceApplication {

	public static void main(String[] args) {
		SpringApplication.run(EcommerceApplication.class, args);
	}
}
Create the User model class with the jpa annotations for mapping java object to database table as follows-
package com.javainuse.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "user")
public class User {

	@Id
	@Column(name = "id")
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Column(name = "name")
	private String name;

	@Column(name = "password")
	private String password;

	@Column(name = "type")
	private String type;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}

Create the repository by extending the JpaRepository. By extending JpaRepository we get a bunch of generic CRUD methods into our type that allows saving Users, deleting and retrieving.
package com.javainuse.db;

import org.springframework.data.jpa.repository.JpaRepository;

import com.javainuse.model.User;

public interface UserRepository extends JpaRepository<User, Long> {
}
@RequestMapping maps /get request to return a list of users. Also here we are using CrossOrigin annotation to specify that calls will be made to this controller from different domains. In our case we have specified that a call can be made from localhost:4200.
   



package com.javainuse.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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.javainuse.db.UserRepository;
import com.javainuse.model.User;

@RestController
@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(path = "users")
public class UserController {

	@Autowired
	private UserRepository userRepository;
	
	@GetMapping("/get")
	public List<User> getUsers() {
		return userRepository.findAll();
	}

}
Define the application file to specify the mysql properties-
spring.datasource.url=jdbc:mysql://localhost/ecommerce?createDatabaseIfNotExist=true&autoReconnect=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.platform=mysql
spring.datasource.initialization-mode=always
spring.jpa.hibernate.ddl-auto=update
spring.jackson.serialization.fail-on-empty-beans=false
Compile and the run the SpringBootHelloWorldApplication.java as a Java application.
Go to localhost:8080/users/get

Currently no records are present in users table. Insert a record in users table and again make the REST call
Insert into user(id,name,password,type) values (1,'javainuse','javainuse','admin');


Go to localhost:8080/users/get

Angular Code

The User Admin will be having the following components -
  • Users Component - List the existing users.
  • User Detail Component - Select existing user to get the user details. Using this component we can also delete the existing user
  • Add User Component - Add new user.
In this tutorial we will be implementing the Users component to display the list of existing users. In the next tutorials we will be developing the User Detail and Add User Component.
We will be modifying the angular code we created in the previous tutorial for adding menu component.
Create a component named users as follows-    
ng generate component admin/users


This component will fetch the existing users from the backend and display it. In the beginning we will be mocking the user list, later we will fetch it from the spring boot back end.
Create a class named User  
   export class User {
    id: number;
    name: string;
    type: string;  
    password: string;
  }
In the users component create an array of type User. We will be initializing this user array in the ngOnInit method of the user component and mock it.
import { Component, OnInit } from '@angular/core';
import { User } from '../../model/User';

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

  users: Array<User>;

  constructor() { }

  ngOnInit() {
    this.users = new Array<User>();

    const user1 = new User();
    user1.id = 1;
    user1.name = 'user1';
    user1.type = 'admin';
    user1.password = 'pass';

    const user2 = new User();
    user2.id = 2;
    user2.name = 'user2';
    user2.type = 'user';
    user2.password = 'pass';

    this.users.push(user1);
    this.users.push(user2);
  }

}
The page Structure for the User-Admin Page will be as follows-

Modify the user component html to display the user list using ngFor directive.
<h1>Users Admin</h1>
<div class="container row">
    <div   class="col-md-6">
    <table class="table">
      <thead>
      <tr>
        <th>ID</th>
        <th>Name</th>
        <th></th>
      </tr>
      </thead>
      <tbody>
      <tr *ngFor="let user of users" >
        <td>{{user.id}}</td>
        <td>{{user.name}}</td>
        <td><button type="button" class="btn btn-primary">Show Details</button></td>
      </tr>
      </tbody>
    </table>
  </div>
  <div   class="col-md-6">
    Display User Details and Add user here.
  </div>
</div>
Next we will be modifying the app routing to define the route for the user component-
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UsersComponent } from './admin/users/users.component';

const routes: Routes = [
  { path: 'admin/users', component: UsersComponent }
];

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

Start the application and go to localhost:4200/admin/users

Next we will be creating a HTTPClient Service. This service will be having the httpClient and will be responsible for calling http GET request to the backend spring boot application. In Angular a service is written for any cross cutting concerns and may be used by more than one components        
    ng generate service service/httpClient
           

    The following service files are created-
  • http-client.service.ts
  • http-client.service.spec.ts
We will be modifying the http-client.service.ts file. In the constructor define the HTTPClient instance we  will be using to make a call to the Spring Boot application.  Here we will be using the Angular HTTPClient for calling the Spring Boot API to fetch the user data.   Also we will creating a method which makes call to the spring boot application using the defined httpClient.    
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

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

  constructor(
    private httpClient:HttpClient
  ) { 
     }

     getUsers()
  {
    return this.httpClient.get<User[]>('http://localhost:8080/users/get');
  }
}
Also we need to add the HTTPClientModule to the app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { MenuComponent } from './menu/menu.component';
import { FooterComponent } from './footer/footer.component';
import { UsersComponent } from './admin/users/users.component';
import { HttpClientModule } from '@angular/common/http';


@NgModule({
  declarations: [
    AppComponent,
    MenuComponent,
    FooterComponent,
    UsersComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
Next using constructor dependency injection we will be providing the UsersComponent an instance of HttpClientService. Using this service we make a call to spring boot application to get a list of users.
import { Component, OnInit } from '@angular/core';
import { User } from '../../model/User';
import { HttpClientService } from '../../service/http-client.service';

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

  users: Array<User>;

  constructor(private httpClientService: HttpClientService) { }

  ngOnInit() {
    this.httpClientService.getUsers().subscribe(
      response => this.handleSuccessfulResponse(response),
    );
  }

  handleSuccessfulResponse(response) {
    this.users = response;
  }

}
Start the Spring Boot Application and also the Angular application. Go to localhost:4200/admin/users
 

Next we will be adding the admin/users link in the menu. Modify the menu.html as follows-
<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 class="nav-item dropdown">
                <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown"
                    aria-haspopup="true" aria-expanded="false">
                    Admin
                </a>
                <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a routerLink="/admin/users">Users</a>
                </div>
            </li>
        </ul>
    </nav>
</header>


Download Source Code

Download it -
Spring Boot + Ecommerce
Angular8 Online Book Store

 

See Also

Spring Boot Hello World Application- Create simple controller and jsp view using Maven Spring Boot Tutorial-Spring Data JPA Spring Boot + Simple Security Configuration Pagination using Spring Boot Simple Example Spring Boot + ActiveMQ Hello world Example Spring Boot + Swagger Example Hello World Example Spring Boot + Swagger- Understanding the various Swagger Annotations Spring Boot Main Menu Spring Boot Interview Questions