Developing Material Category Management for a Warehouse System

Warehouse System - Item Cateogry ManagementImplementing Item Category Management

This section details the implementation of a material category management module for a warehouse system. The module allows administrators to create, read, update, and delete item categories, which are used to organize inventory items.

1. Data Model: ItemCategory

The ItemCategory class represents the data structure for a material cateogry. It encapsulates the category's unique identifier, code, name, and description.

package com.warehouse.model;

public class ItemCategory {
    private int id;
    private String code;
    private String name;
    private String description;

    // Default constructor
    public ItemCategory() {}

    // Parameterized constructor for creating new categories
    public ItemCategory(String code, String name, String description) {
        this.code = code;
        this.name = name;
        this.description = description;
    }

    // Getters and Setters
    public int getId() {
        return id;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}

2. Controller: ItemCategoryController

The ItemCategoryController is a servlet responsible for handling HTTP requests related to item categories. The example below shows the logic for adding a new category.

package com.warehouse.controller;

import com.google.gson.Gson;
import com.warehouse.dao.ItemCategoryDAO;
import com.warehouse.model.ItemCategory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/categories/add")
public class ItemCategoryController extends HttpServlet {
    private ItemCategoryDAO itemCategoryDAO = new ItemCategoryDAO();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve parameters from the request
        String code = request.getParameter("code");
        String name = request.getParameter("name");
        String description = request.getParameter("description");

        // Create a new ItemCategory object
        ItemCategory newCategory = new ItemCategory(code, name, description);
        
        // Attempt to add the category to the database
        boolean success = itemCategoryDAO.addItemCategory(newCategory);

        // Send a response back to the client
        response.setContentType("application/json");
        response.getWriter().write(new Gson().toJson(new Response(success)));
    }

    // A simple response object for JSON
    private static class Response {
        private boolean success;
        public Response(boolean success) { this.success = success; }
    }
}

3. Data Access Object (DAO): ItemCategoryDAO

The ItemCategoryDAO class contains the database interaction logic for performing CRUD operations on the ItemCategory entity.

package com.warehouse.dao;

import com.warehouse.model.ItemCategory;
import com.warehouse.util.DBUtil;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ItemCategoryDAO {

    public boolean addItemCategory(ItemCategory category) {
        String sql = "INSERT INTO item_categories (code, name, description) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, category.getCode());
            pstmt.setString(2, category.getName());
            pstmt.setString(3, category.getDescription());
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean updateItemCategory(ItemCategory category) {
        String sql = "UPDATE item_categories SET code = ?, name = ?, description = ? WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, category.getCode());
            pstmt.setString(2, category.getName());
            pstmt.setString(3, category.getDescription());
            pstmt.setInt(4, category.getId());
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean deleteItemCategory(int id) {
        String sql = "DELETE FROM item_categories WHERE id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, id);
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    public List<itemcategory> getAllItemCategories() {
        String sql = "SELECT * FROM item_categories";
        List<itemcategory> categories = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                ItemCategory category = new ItemCategory(
                        rs.getString("code"),
                        rs.getString("name"),
                        rs.getString("description")
                );
                category.setId(rs.getInt("id"));
                categories.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return categories;
    }
}
</itemcategory></itemcategory>

4. Frontend Interaction (React Example)

The following React component demonstrates how a front end application might interact with the ItemCategoryController to add a new category. It uses the Fetch API to send a POST request.

import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';

const AddCategoryForm = () => {
    const [form] = Form.useForm();

    const handleFinish = (values) => {
        fetch('/api/categories/add', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams(values).toString(),
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                message.success('Category added successfully!');
                form.resetFields();
            } else {
                message.error('Failed to add category.');
            }
        })
        .catch(error => {
            message.error('An error occurred.');
            console.error('Error:', error);
        });
    };

    return (
        <form description:="" form="{form}" initialvalues="{{" layout="vertical" onfinish="{handleFinish}">
            </form><form.item category="" code="" input="" label="Category Code" message:="" name="code" required:="" rules="{[{" the="" true="">
                <input></input>
            </form.item>
            <form.item category="" input="" label="Category Name" message:="" name="name" required:="" rules="{[{" the="" true="">
                <input></input>
            </form.item>
            <form.item label="Description" name="description">
                <input.textarea></input.textarea>
            </form.item>
            <form.item>
                <button htmltype="submit" type="primary">
                    Add Category
                </button>
            </form.item>
        
    );
};

export default AddCategoryForm;

Tags: java servlet JDBC React Warehouse Management

Posted on Fri, 11 Sep 2026 16:27:31 +0000 by TheKiller