Controller Layer

In Inventory Management System, The Controller class is created by using @Controller Annotation. This class is handled the incoming API requests, based on the request type it can provide like post,get,delete like that. It can trigger the business logic and provide the output on the web page by using Thymeleaf Framework.

ProductController.class:

Java




package com.ims.app.controller;
  
import java.util.List;
import java.util.Optional;
import java.util.Random;
  
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  
import com.ims.app.model.Product;
import com.ims.app.service.ProductService;
  
@Controller
public class ProductController {
  
    @Autowired
    private ProductService productService;
  
    @GetMapping("/")
    public String getIndexPage(Model model) {
        List<Product> productList = productService.getAllProducts();
        model.addAttribute("products", productList);
        model.addAttribute("product", new Product());
        return "index";
    }
  
    @PostMapping("/newProduct")
    public String newProduct(@ModelAttribute("product") Product product, RedirectAttributes redirectAttributes) {
        // Creating dynamic product ID
        String productId = "PD" + (1000 + new Random().nextInt(9000));
        product.setId(productId);
        productService.addProduct(product);
        redirectAttributes.addFlashAttribute("insertSuccess", true);
        return "redirect:/";
    }
  
    @PostMapping("/searchProduct")
    public String searchProduct(@RequestParam(name = "id") String id, RedirectAttributes redirectAttributes,
            Model model) {
        Optional<Product> foundProduct = productService.getProductById(id);
        model.addAttribute("product", new Product());
        if (foundProduct.isPresent()) {
            redirectAttributes.addFlashAttribute("foundProduct", foundProduct);
        } else {
            redirectAttributes.addFlashAttribute("notFound", true);
        }
  
        return "redirect:/";
    }
  
    @PostMapping("/deleteProduct")
    public String deleteProduct(@RequestParam(name = "id") String id, RedirectAttributes redirectAttributes) {
        boolean deleteSuccess = productService.deleteProductById(id);
        if (deleteSuccess) {
            redirectAttributes.addFlashAttribute("deleteSuccess", true);
        } else {
            redirectAttributes.addFlashAttribute("notFound", true);
        }
  
        return "redirect:/";
    }
  
    @GetMapping("/productAnalysis")
    public String productAnalysis(Model model) {
        List<Product> products = productService.getAllProducts();
        model.addAttribute("products", products);
        return "productAnalysis"; // Thymeleaf template name
    }
      
}


The above code performs different operations like display the HTML index page, adding product details as well as display the analysis report of the Product.

  • @GetMapping(“/productAnalysis”) is used for displaying the Product Analysis report
  • @GetMapping(“/”) is used for displaying the entire html page
  • @PostMapping(“/newProduct”) is used for inserting new product details into system
  • @PostMapping(“/searchProduct”) is used for searching an existing product detail by using product ID
  • @PostMapping(“/deleteProduct”) is used for deleting a product from database using product ID

Display HTML Page:

For displaying the index.html page I used Thymeleaf for integrating back-end logic with front-end view. By using GET API request.

Java




@GetMapping("/")
    public String getIndexPage(Model model) {
        List<Product> productList = productService.getAllProducts();
        model.addAttribute("products", productList);
        model.addAttribute("product", new Product());
        return "index";
    }


index page:

Insert New Product Details

We can able to insert new product data by the help of ProductRepo interface. This Repository provide one method that is save method. This method is used for save data in database.

Java




@PostMapping("/newProduct")
    public String newProduct(@ModelAttribute("product") Product product, RedirectAttributes redirectAttributes) {
        // Creating dynamic product ID
        String productId = "PD" + (1000 + new Random().nextInt(9000));
        product.setId(productId);
        productService.addProduct(product);
        redirectAttributes.addFlashAttribute("insertSuccess", true);
        return "redirect:/";
    }


Add product:

For Inserting Product details, here we have created one POST mapping for saving product data. When You call this API one HTML Form is opened and it will ask some detail about the product once submitted that data. By using Random method, we have generated one Unique number for that number as PD as prefix, after that con-cat both of them then we get Unique Product ID.

Search Product Details

We can search a product detail by using product ID. If Product details are existed, It display the product details otherwise The Thymeleaf show one Alert message for no data exist.

Java




@PostMapping("/searchProduct")
    public String searchProduct(@RequestParam(name = "id") String id, RedirectAttributes redirectAttributes,
            Model model) {
        Optional<Product> foundProduct = productService.getProductById(id);
        model.addAttribute("product", new Product());
        if (foundProduct.isPresent()) {
            redirectAttributes.addFlashAttribute("foundProduct", foundProduct);
        } else {
            redirectAttributes.addFlashAttribute("notFound", true);
        }
  
        return "redirect:/";
    }


Search Product Details:

If want to search any product detail, we need product ID then only we able search product details. For this we have created one POST API, that is searchProduct. When we hit this API, it will open one form and ask product ID then Click on Search Button. If product ID is not existed, it will show one alert message to you.

Delete Product

Delete a product by using Its ID, for this we have created one POST method API. When you hit API, it will ask you product ID. If you provide valid ID, then product is removed from database otherwise it will show one error message like alert message.

Java




@PostMapping("/deleteProduct")
    public String deleteProduct(@RequestParam(name = "id") String id, RedirectAttributes redirectAttributes) {
        boolean deleteSuccess = productService.deleteProductById(id);
        if (deleteSuccess) {
            redirectAttributes.addFlashAttribute("deleteSuccess", true);
        } else {
            redirectAttributes.addFlashAttribute("notFound", true);
        }
  
        return "redirect:/";
    }


Delete Product:

After Deleting Existing Product:

After successful product deletion It will redirect to Home page tab.

Product Report

Here we have created one basic product report on maximum and minimum number of product items with their category. For charts creation we have used chart js cdn.

Java




@GetMapping("/productAnalysis")
    public String productAnalysis(Model model) {
        List<Product> products = productService.getAllProducts();
        model.addAttribute("products", products);
        return "productAnalysis"; // Thymeleaf template name
    }


Report Page:

Inventory Management System using Spring Boot

Inventory Management System plays an important role in Business for tracking the Inventory, and It is used for tracking and movement of goods. In this article, we have provided some basic functionality for the Inventory Management System like an Analysis report of goods, adding new Products to the System, Searching the existing product details, and other one is deleting an existing product from the System. In this article, we have mentioned an Inventory Management System as an IMS App, for this tool we have used Spring Boot with an MVC pattern with Thymeleaf for front-end integration.

This Application handles the product details and performs different operations on every record in the Inventory Management System Application.

Prerequisites

  • Spring Boot
  • Thymeleaf
  • MongoDB
  • Spring MVC Pattern
  • Bootstrap Framework
  • Project Type is Gradle
  • Spring Tool Suite IDE (STS)

This Spring Boot Inventory Management System Web Application with MVC Pattern and the Thymeleaf is used for providing Dynamic HTML content in this tool, The MongoDB is used for data storage purposes, and the other one is Bootstrap framework used for creating responsive web applications.

Product Details

For a Product, we have different attributes like:

  • Product ID
  • Product Category
  • Product Name
  • Product Rating
  • Quality
  • Maximum number of Products
  • Minimum number of Products
  • Username (Product Added by)
  • User Email Address
  • User Phone Number

In this Inventory Management System Project, the Product ID is dynamically Generated which have String and Number format. After Generating Product ID then Inserted Other product detail with ID in the Database.

Project Creation Steps

  • Create a Spring Stater Project using Spring Tool Suite IDE ( reference )
  • After successfully creation of Project, then create Package for different layers in this web Application namely packages for Controller, POJO, Repository and other packages if you want.
  • In Controller Package create one ProductController class after that create one Project POJO class in POJO package, After Create one Product Repository interface in Repository package. After that create one HTML file in the Templates which is placed in project resource folder.
  • Now Implement Controller layer code after that develop pojo class code, after that develop repository class code.
  • After completion of Back-end functionalities then develop the front-end page for visibility.
  • After successfully completion of Front-End and Back-End then Integrate both of them by using Thymeleaf Framework.
  • After that Run this Application as Spring Boot App.

Required Project Dependencies

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

Note: These Project Dependencies are available in Spring Stater Project While creating the Project. After Creation of this Project You can see These Dependencies in build.gradle file in the Project.

Project Folder Structure

Code Development Process

Now we will see the development Process of Inventory Management System using Spring Boot, Spring MVC. In development process first we create one POJO class for Products. In this POJO class we keep Attributes of Product like Product ID, Like Product Category, Product Name, Product Rating, Quality, Maximum number of Products, Minimum number of Products, Username (Product Added by), User Email Address, User Phone Number. This POJO class also have Setters and Getters methods for data handling with Parameterized and non-Parameterized constructors in Product POJO class.

Database Connection

In Inventory Management System Application, We perform different Operation on data. That’s why we need a data storage for storing the data. For this I Selected MongoDB Database for data Storage. In Database Connection We need three attribute values those Host name, Port number of MongoDB, And the other one is Database Name. The Database Connection Attributes keep in application properties file. We have already provided the folder structure. In that application properties file is available.

# database properties
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
spring.data.mongodb.database=ims

# thymeleaf configuration
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

Note : Here ims is the Database name, 27017 is the port number of MongoDB, And we have used Localhost for running the system on my local system.

Similar Reads

Model Layer

For this, we have created one POJO class in pojo package that is Product.class, this POJO class contains all the attributes of the Product and It have Setters and Getters and also two different constructors like Parameterized and non-Parameterized constructors. And I used one dependency that is lombok which is available in Spring Boot. This Annotation is used for Parameterized and non-Parameterized constructors by using @Data, @AllArgsConstructor, @NoArgsConstructor, @Document....

View Layer

...

Controller Layer

For View Purpose we have created one HTML page in Templates folder in the Project Folder Structure. And we have used Thymeleaf for Providing Dynamic Content of The HTML page in the Inventory Management System Project....

Conclusion

...

Contact Us