ai之我要生成仓库管理系统

概述:一开始,我将文档中的所有要求全部抛给ai,之后,我先把ai的部分代码放入idea中运行尝试。然后,先做完了登录注册页面和数据库的连接,之后对于登录之后的页面跳转和功能实现,再一次抛给ai生成,增加了servlet和service还有jsp部分对应的仓库CRUD的代码。
1.框架:


2.SQL语句:

create table users
(
    id       int auto_increment
        primary key,
    username varchar(50)  not null,
    password varchar(255) not null,
    role     varchar(20)  not null
);

-- auto-generated definition
create table warehouse
(
    warehouse_id   varchar(20)  not null
        primary key,
    warehouse_name varchar(100) not null,
    address        varchar(200) null,
    remark         text         null
);


-- auto-generated definition
create table material_category
(
    material_code varchar(20)  not null
        primary key,
    material_name varchar(100) not null,
    specification varchar(50)  null,
    material      text         null,
    constraint material_name
        unique (material_name, specification, material(255))
);


-- auto-generated definition
create table material_ledger_detail
(
    ledger_id      varchar(14)           not null
        primary key,
    material_code  varchar(20)           not null,
    operation_type enum ('入库', '出库') not null,
    quantity       decimal(10, 2)        not null,
    unit           varchar(20)           not null,
    warehouse_id   varchar(20)           not null,
    operation_date date                  not null,
    remark         text                  null,
    constraint material_ledger_detail_ibfk_1
        foreign key (material_code) references material_category (material_code),
    constraint material_ledger_detail_ibfk_2
        foreign key (warehouse_id) references warehouse (warehouse_id)
);

create index material_code
    on material_ledger_detail (material_code);

create index warehouse_id
    on material_ledger_detail (warehouse_id);


3.bean包:(图片中的后三个没有用,所以没有放出来)

package bean;

public class MaterialCategory {

    // 物资编码,唯一标识物资类别
    private String materialCode;
    // 物资名称
    private String materialName;
    // 物资规格
    private String specification;
    // 物资材质
    private String material;

    // 无参构造方法,方便创建空对象
    public MaterialCategory() {
    }

    // 有参构造方法,用于创建对象时初始化属性
    public MaterialCategory(String materialCode, String materialName, String specification, String material) {
        this.materialCode = materialCode;
        this.materialName = materialName;
        this.specification = specification;
        this.material = material;
    }

    // 获取物资编码
    public String getMaterialCode() {
        return materialCode;
    }

    // 设置物资编码
    public void setMaterialCode(String materialCode) {
        this.materialCode = materialCode;
    }

    // 获取物资名称
    public String getMaterialName() {
        return materialName;
    }

    // 设置物资名称
    public void setMaterialName(String materialName) {
        this.materialName = materialName;
    }

    // 获取物资规格
    public String getSpecification() {
        return specification;
    }

    // 设置物资规格
    public void setSpecification(String specification) {
        this.specification = specification;
    }

    // 获取物资材质
    public String getMaterial() {
        return material;
    }

    // 设置物资材质
    public void setMaterial(String material) {
        this.material = material;
    }

    // 重写 toString 方法,方便打印对象信息
    @Override
    public String toString() {
        return "MaterialCategory{" +
                "materialCode='" + materialCode + '\'' +
                ", materialName='" + materialName + '\'' +
                ", specification='" + specification + '\'' +
                ", material='" + material + '\'' +
                '}';
    }
}
package bean;



public class User {
    private int id;//用户ID
    private String username;//用户名
    private String password;//密码
    private String role;//角色

    public static void main(String[] args) {
        System.out.println();
    }


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

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

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

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }
}
package bean;


// 仓库实体类,用于封装仓库信息
public class Warehouse {
    // 仓库编号
    private String warehouseId;
    // 仓库名称
    private String warehouseName;
    // 仓库地址
    private String address;
    // 仓库备注信息
    private String remark;

    // 无参构造方法
    public Warehouse() {
    }

    // 有参构造方法,方便初始化对象
    public Warehouse(String warehouseId, String warehouseName, String address, String remark) {
        this.warehouseId = warehouseId;
        this.warehouseName = warehouseName;
        this.address = address;
        this.remark = remark;
    }

    // 获取仓库编号
    public String getWarehouseId() {
        return warehouseId;
    }

    // 设置仓库编号
    public void setWarehouseId(String warehouseId) {
        this.warehouseId = warehouseId;
    }

    // 获取仓库名称
    public String getWarehouseName() {
        return warehouseName;
    }

    // 设置仓库名称
    public void setWarehouseName(String warehouseName) {
        this.warehouseName = warehouseName;
    }

    // 获取仓库地址
    public String getAddress() {
        return address;
    }

    // 设置仓库地址
    public void setAddress(String address) {
        this.address = address;
    }

    // 获取仓库备注信息
    public String getRemark() {
        return remark;
    }

    // 设置仓库备注信息
    public void setRemark(String remark) {
        this.remark = remark;
    }

    @Override
    public String toString() {
        return "Warehouse{" +
                "warehouseId='" + warehouseId + '\'' +
                ", warehouseName='" + warehouseName + '\'' +
                ", address='" + address + '\'' +
                ", remark='" + remark + '\'' +
                '}';
    }
}

4.service包:

package service;

import bean.MaterialCategory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class MaterialCategoryDao {
    private static final String URL = "jdbc:mysql://localhost:3306/tree?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    // 新增物资类别
    public boolean addMaterialCategory(String materialCode, String materialName, String specification, String material) {
        String sql = "INSERT INTO material_category (material_code, material_name, specification, material) VALUES (?,?,?,?)";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, materialCode);
            pstmt.setString(2, materialName);
            pstmt.setString(3, specification);
            pstmt.setString(4, material);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除物资类别
    public boolean deleteMaterialCategory(String materialCode) {
        String sql = "DELETE FROM material_category WHERE material_code = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, materialCode);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 修改物资类别信息
    public boolean updateMaterialCategory(String materialCode, String materialName, String specification, String material) {
        String sql = "UPDATE material_category SET material_name = ?, specification = ?, material = ? WHERE material_code = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, materialName);
            pstmt.setString(2, specification);
            pstmt.setString(3, material);
            pstmt.setString(4, materialCode);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取所有物资类别信息
    public List<MaterialCategory> getAllMaterialCategories() {
        List<MaterialCategory> categories = new ArrayList<>();
        String sql = "SELECT * FROM material_category";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                MaterialCategory category = new MaterialCategory();
                category.setMaterialCode(rs.getString("material_code"));
                category.setMaterialName(rs.getString("material_name"));
                category.setSpecification(rs.getString("specification"));
                category.setMaterial(rs.getString("material"));
                categories.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return categories;
    }
}
package service; // 你可以根据项目结构调整包名

import bean.User;
import utils.jdbcUtils;

import java.sql.*;

public class UserService {
    // 假设你已经有了 DBConnection 类用于获取数据库连接
    private static final String URL = "jdbc:mysql://localhost:3306/tree?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    public static void main(String[] args) {
        try (Connection conn = jdbcUtils.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM your_table_name")) {
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                System.out.println("ID: " + id + ", Name: " + name);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public User login(String username, String password) {
        String sql = "SELECT * FROM users WHERE username = ? AND password = ?";
        try (Connection conn = jdbcUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setRole(rs.getString("role"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public boolean register(String username, String password, String role) {
        String sql = "INSERT INTO users (username, password, role) VALUES (?, ?, ?)";
        try (Connection conn = jdbcUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, role);
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }
}
package service;

import bean.Warehouse;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class WarehouseDao {
    private static final String URL = "jdbc:mysql://localhost:3306/tree?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";

    // 新增仓库
    public boolean addWarehouse(String warehouseId, String warehouseName, String address, String remark) {
        String sql = "INSERT INTO warehouse (warehouse_id, warehouse_name, address, remark) VALUES (?,?,?,?)";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, warehouseId);
            pstmt.setString(2, warehouseName);
            pstmt.setString(3, address);
            pstmt.setString(4, remark);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 删除仓库
    public boolean deleteWarehouse(String warehouseId) {
        String checkSql = "SELECT COUNT(*) FROM material_ledger_detail WHERE warehouse_id = ?";
        String deleteSql = "DELETE FROM warehouse WHERE warehouse_id = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            try (PreparedStatement checkPstmt = conn.prepareStatement(checkSql)) {
                checkPstmt.setString(1, warehouseId);
                ResultSet rs = checkPstmt.executeQuery();
                if (rs.next() && rs.getInt(1) == 0) {
                    try (PreparedStatement deletePstmt = conn.prepareStatement(deleteSql)) {
                        deletePstmt.setString(1, warehouseId);
                        return deletePstmt.executeUpdate() > 0;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 修改仓库信息
    public boolean updateWarehouse(String warehouseId, String warehouseName, String address, String remark) {
        String checkSql = "SELECT COUNT(*) FROM material_ledger_detail WHERE warehouse_id = ?";
        String updateSql = "UPDATE warehouse SET warehouse_name = ?, address = ?, remark = ? WHERE warehouse_id = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD)) {
            try (PreparedStatement checkPstmt = conn.prepareStatement(checkSql)) {
                checkPstmt.setString(1, warehouseId);
                ResultSet rs = checkPstmt.executeQuery();
                if (rs.next() && rs.getInt(1) == 0) {
                    try (PreparedStatement updatePstmt = conn.prepareStatement(updateSql)) {
                        updatePstmt.setString(1, warehouseName);
                        updatePstmt.setString(2, address);
                        updatePstmt.setString(3, remark);
                        updatePstmt.setString(4, warehouseId);
                        return updatePstmt.executeUpdate() > 0;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public Warehouse getWarehouseById(String warehouseId) {
        String sql = "SELECT * FROM warehouse WHERE warehouse_id = ?";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            // 设置查询参数
            pstmt.setString(1, warehouseId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    Warehouse warehouse = new Warehouse();
                    // 从结果集中获取数据并设置到 Warehouse 对象中
                    warehouse.setWarehouseId(rs.getString("warehouse_id"));
                    warehouse.setWarehouseName(rs.getString("warehouse_name"));
                    warehouse.setAddress(rs.getString("address"));
                    warehouse.setRemark(rs.getString("remark"));
                    return warehouse;
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    // 获取所有仓库信息
    public List<Warehouse> getAllWarehouses() {
        List<Warehouse> warehouses = new ArrayList<>();
        String sql = "SELECT * FROM warehouse";
        try (Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                Warehouse warehouse = new Warehouse();
                warehouse.setWarehouseId(rs.getString("warehouse_id"));
                warehouse.setWarehouseName(rs.getString("warehouse_name"));
                warehouse.setAddress(rs.getString("address"));
                warehouse.setRemark(rs.getString("remark"));
                warehouses.add(warehouse);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return warehouses;
    }


}

5.servlet包:

package servlet;

import service.MaterialCategoryDao;

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("/adminMaterialCategory")
public class AdminMaterialCategoryServlet extends HttpServlet {
    private MaterialCategoryDao materialCategoryDao = new MaterialCategoryDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        if ("add".equals(action)) {
            String materialCode = req.getParameter("materialCode");
            String materialName = req.getParameter("materialName");
            String specification = req.getParameter("specification");
            String material = req.getParameter("material");
            if (materialCategoryDao.addMaterialCategory(materialCode, materialName, specification, material)) {
                resp.getWriter().println("物资类别添加成功");
            } else {
                resp.getWriter().println("物资类别添加失败");
            }
        } else if ("delete".equals(action)) {
            String materialCode = req.getParameter("materialCode");
            if (materialCategoryDao.deleteMaterialCategory(materialCode)) {
                resp.getWriter().println("物资类别删除成功");
            } else {
                resp.getWriter().println("物资类别删除失败");
            }
        } else if ("update".equals(action)) {
            String materialCode = req.getParameter("materialCode");
            String materialName = req.getParameter("materialName");
            String specification = req.getParameter("specification");
            String material = req.getParameter("material");
            if (materialCategoryDao.updateMaterialCategory(materialCode, materialName, specification, material)) {
                resp.getWriter().println("物资类别信息修改成功");
            } else {
                resp.getWriter().println("物资类别信息修改失败");
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("materialCategories", materialCategoryDao.getAllMaterialCategories());
        req.getRequestDispatcher("adminMaterialCategory.jsp").forward(req, resp);
    }
}
package servlet;

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;
import service.WarehouseDao;

@WebServlet("/WarehouseDao")
public class AdminWarehouseServlet extends HttpServlet {
    private WarehouseDao warehouseDao = new WarehouseDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8,防止中文乱码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html; charset=UTF-8");

        String action = req.getParameter("action");
        if ("add".equals(action)) {
            // 获取表单提交的仓库信息
            String warehouseId = req.getParameter("warehouseId");
            String warehouseName = req.getParameter("warehouseName");
            String address = req.getParameter("address");
            String remark = req.getParameter("remark");

            if (warehouseDao.addWarehouse(warehouseId, warehouseName, address, remark)) {
                // 仓库添加成功,跳转到仓库列表页面
                req.getRequestDispatcher("/warehouseList.jsp").forward(req, resp);
            } else {
                // 仓库添加失败,输出错误信息
                resp.getWriter().println("仓库添加失败");
            }
        } else if ("delete".equals(action)) {
            // 处理删除仓库的逻辑
            String warehouseId = req.getParameter("warehouseId");
            if (warehouseDao.deleteWarehouse(warehouseId)) {
                resp.getWriter().println("仓库删除成功");
            } else {
                resp.getWriter().println("仓库删除失败,可能有物资存储在该仓库");
            }
        } else if ("update".equals(action)) {
            // 处理更新仓库信息的逻辑
            String warehouseId = req.getParameter("warehouseId");
            String warehouseName = req.getParameter("warehouseName");
            String address = req.getParameter("address");
            String remark = req.getParameter("remark");
            if (warehouseDao.updateWarehouse(warehouseId, warehouseName, address, remark)) {
                resp.getWriter().println("仓库信息修改成功");
            } else {
                resp.getWriter().println("仓库信息修改失败,可能有物资存储在该仓库");
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理 GET 请求,例如显示仓库列表
        req.setAttribute("warehouses", warehouseDao.getAllWarehouses());
        req.getRequestDispatcher("warehouseList.jsp").forward(req, resp);
    }
}
package servlet;

import bean.User;
import service.UserService;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = userService.login(username, password);
        if (user != null) {
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            response.sendRedirect("dashboard.jsp");
        } else {
            request.setAttribute("error", "Invalid username or password");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}
package servlet;

import service.UserService;

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("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String role = request.getParameter("role");

        if (userService.register(username, password, role)) {
            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("错误", "注册失败,请重试!");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}
package servlet;
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;
import bean.Warehouse;
import service.WarehouseDao;

@WebServlet("/SomeServlet")
public class SomeServlet extends HttpServlet {
    private WarehouseDao warehouseDao = new WarehouseDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String warehouseId = req.getParameter("warehouseId");
        Warehouse warehouse = warehouseDao.getWarehouseById(warehouseId);
        if (warehouse != null) {
            // 处理仓库信息
            String id = warehouse.getWarehouseId();
            // 其他操作
        } else {
            // 处理仓库记录不存在的情况
            resp.getWriter().println("未找到对应的仓库记录");
        }
    }
}
package servlet;
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;
import bean.Warehouse;
import service.WarehouseDao;

@WebServlet("/SomeServlet")
public class SomeServlet extends HttpServlet {
    private WarehouseDao warehouseDao = new WarehouseDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String warehouseId = req.getParameter("warehouseId");
        Warehouse warehouse = warehouseDao.getWarehouseById(warehouseId);
        if (warehouse != null) {
            // 处理仓库信息
            String id = warehouse.getWarehouseId();
            // 其他操作
        } else {
            // 处理仓库记录不存在的情况
            resp.getWriter().println("未找到对应的仓库记录");
        }
    }
}
package servlet;

import bean.Warehouse;
import service.WarehouseDao;

import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/WarehouseServlet")
public class WarehouseServlet extends HttpServlet {
    private WarehouseDao warehouseDao = new WarehouseDao();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        // 处理请求的代码
        String action = request.getParameter("action");

        if (action == null) {
            // 显示仓库列表
            List<Warehouse> warehouses = warehouseDao.getAllWarehouses();
            request.setAttribute("warehouses", warehouses);
            request.getRequestDispatcher("warehouseList.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            // 编辑仓库信息
            String warehouseId = request.getParameter("warehouseId");
            Warehouse warehouse = warehouseDao.getWarehouseById(warehouseId);
            request.setAttribute("warehouse", warehouse);
            request.getRequestDispatcher("editWarehouse.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            // 删除仓库
            String warehouseId = request.getParameter("warehouseId");
            boolean result = warehouseDao.deleteWarehouse(warehouseId);
            if (result) {
                response.getWriter().println("删除成功");
            } else {
                response.getWriter().println("该仓库有相关物资存储,不允许删除");
            }
            List<Warehouse> warehouses = warehouseDao.getAllWarehouses();
            request.setAttribute("warehouses", warehouses);
            request.getRequestDispatcher("yourJspPage.jsp").forward(request, response);
            response.sendRedirect("WarehouseServlet");
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String action = request.getParameter("action");
        if (action.equals("add")) {
            // 新增仓库
            Warehouse warehouse = new Warehouse();
            warehouse.setWarehouseId(request.getParameter("warehouseId"));
            warehouse.setWarehouseName(request.getParameter("warehouseName"));
            warehouse.setAddress(request.getParameter("address"));
            warehouse.setRemark(request.getParameter("remark"));
            boolean result = warehouseDao.addWarehouse(warehouse.getWarehouseId(),warehouse.getWarehouseName(),warehouse.getAddress(),warehouse.getRemark());
            if (result) {
                response.getWriter().println("新增成功");
            } else {
                response.getWriter().println("新增失败");
            }
            response.sendRedirect("WarehouseServlet");
        } else if (action.equals("update")) {
            // 修改仓库信息
            Warehouse warehouse = new Warehouse();
            warehouse.setWarehouseId(request.getParameter("warehouseId"));
            warehouse.setWarehouseName(request.getParameter("warehouseName"));
            warehouse.setAddress(request.getParameter("address"));
            warehouse.setRemark(request.getParameter("remark"));
            boolean result = warehouseDao.updateWarehouse(warehouse.getWarehouseId(),warehouse.getWarehouseName(),warehouse.getAddress(),warehouse.getRemark());
            if (result) {
                response.getWriter().println("修改成功");
            } else {
                response.getWriter().println("该仓库有相关物资存储,不允许修改");
            }
            response.sendRedirect("WarehouseServlet");
        }
    }
}

6.utils包:

package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class jdbcUtils {
    private static final String URL = "jdbc:mysql://localhost:3306/tree?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "123456";
    static {
        try {
            // 加载 MySQL 数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }
}

7.jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>新增仓库</title>
</head>
<body>
<h2>新增仓库</h2>
<form action="WarehouseServlet" method="post">
    <input type="hidden" name="action" value="add">
    <label for="warehouseId">仓库编号:</label>
    <input type="text" id="warehouseId" name="warehouseId" required><br>
    <label for="warehouseName">仓库名称:</label>
    <input type="text" id="warehouseName" name="warehouseName" required><br>
    <label for="address">仓库地址:</label>
    <input type="text" id="address" name="address"><br>
    <label for="remark">备注:</label>
    <textarea id="remark" name="remark"></textarea><br>
    <input type="submit" value="新增">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<h2>物资类别管理</h2>
<h3>新增物资类别</h3>
<form action="dashboard" method="post">
    <input type="hidden" name="action" value="add">
    <label for="materialCode">物资编码:</label>
    <input type="text" id="materialCode" name="materialCode" required><br>
    <label for="materialName">物资名称:</label>
    <input type="text" id="materialName" name="materialName" required><br>
    <label for="specification">物资规格:</label>
    <input type="text" id="specification" name="specification"><br>
    <label for="material">物资材质:</label>
    <input type="text" id="material" name="material"><br>
    <input type="submit" value="新增">
</form>


<%@ page import="bean.Warehouse" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<h2>仓库管理</h2>
<h3>新增仓库</h3>
<form action="WarehouseDao" method="post">
    <input type="hidden" name="action" value="add">
    <label for="warehouseId">仓库编号:</label>
    <input type="text" id="warehouseId" name="warehouseId" required><br>
    <label for="warehouseName">仓库名称:</label>
    <input type="text" id="warehouseName" name="warehouseName" required><br>
    <label for="address">仓库地址:</label>
    <input type="text" id="address" name="address"><br>
    <label for="remark">备注:</label>
    <textarea id="remark" name="remark"></textarea><br>

    <input type="submit" value="新增">
</form>
<h3>现有仓库列表</h3>
<form action="WarehouseListServlet" method="get">
    <input type="submit" value="查看仓库列表">
</form>
<%@ include file="footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<%@ page import="service.WarehouseDao, bean.Warehouse" %>
<%
    String warehouseId = request.getParameter("warehouseId");
    WarehouseDao warehouseDao = new WarehouseDao();
    Warehouse warehouse = warehouseDao.getWarehouseById(warehouseId);
%>
<h2>修改仓库信息</h2>
<form action="dashboard" method="post">
    <input type="hidden" name="action" value="update">
    <input type="hidden" name="warehouseId" value="<%= warehouse.getWarehouseId() %>">
    <label for="warehouseName">仓库名称:</label>
    <input type="text" id="warehouseName" name="warehouseName" value="<%= warehouse.getWarehouseName() %>" required><br>
    <label for="address">仓库地址:</label>
    <input type="text" id="address" name="address" value="<%= warehouse.getAddress() %>"><br>
    <label for="remark">备注:</label>
    <textarea id="remark" name="remark"><%= warehouse.getRemark() %></textarea><br>
    <input type="submit" value="保存修改">
</form>
<%@ include file="footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="bean.User" %>
<%@ include file="header.jsp" %>
<h2>欢迎仓库管理系统</h2>
<%
  User user = (User) session.getAttribute("user");
  if (user != null) {
    out.println("<p>欢迎," + user.getUsername() + "</p>");
    if ("admin".equals(user.getRole())) {
      // 管理员菜单项
      out.println("<ul>");
      // 修改链接地址为仓库管理页面
      out.println("<li><a href='adminMaterialCategory.jsp'>物资管理</a></li>");
      out.println("<li><a href='adminWarehouse.jsp'>仓库管理</a></li>");
      out.println("</ul>");
    } else if ("warehouse".equals(user.getRole())) {
      // 仓库管理人员菜单项
      out.println("<ul>");
      out.println("<li><a href='#'>出库操作</a></li>");
      out.println("<li><a href='#'>入库操作</a></li>");
      out.println("</ul>");
    }
  } else {
    response.sendRedirect("login.jsp");
  }
%>
<%@ include file="footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="bean.Warehouse" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>编辑仓库信息</title>
</head>
<body>
<h2>编辑仓库信息</h2>
<%
    Warehouse warehouse = (Warehouse) request.getAttribute("warehouse");
%>
<form action="WarehouseServlet?action=update" method="post">
    <input type="hidden" name="warehouseId" value="<%= warehouse.getWarehouseId() %>">
    <label for="warehouseName">仓库名称:</label>
    <input type="text" id="warehouseName" name="warehouseName" value="<%= warehouse.getWarehouseName() %>" required><br>
    <label for="address">仓库地址:</label>
    <input type="text" id="address" name="address" value="<%= warehouse.getAddress() %>"><br>
    <label for="remark">备注:</label>
    <textarea id="remark" name="remark"><%= warehouse.getRemark() %></textarea><br>
    <input type="submit" value="保存修改">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<footer>
    <p>© 仓库管理系统</p>
</footer>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <title>仓库管理系统</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
    <h1>仓库管理系统</h1>
    <nav>
        <ul>
            <li><a href="index.jsp">首页</a></li>
            <li><a href="login.jsp">登录</a></li>
            <li><a href="register.jsp">注册</a></li>
        </ul>
    </nav>
</header>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
    <title>Index Page</title>
</head>
<body>
<h1>Welcome to Our System</h1>
<p>Please click the button below to log in.</p>
<a href="login.jsp"><button>Login</button></a>
</body>
</html>




<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<h2>登录</h2>
<% if (request.getAttribute("error") != null) { %>
<p style="color: red;"><%= request.getAttribute("error") %></p>
<% } %>
<form action="login" method="post">
  <label for="username">用户名:</label>
  <input type="text" id="username" name="username" required><br>
  <label for="password">密码:</label>
  <input type="password" id="password" name="password" required><br>
  <input type="submit" value="登录">
</form>
<a href="register.jsp">还没有账号?点击注册</a>
<%@ include file="footer.jsp" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<h2>注册</h2>
<% if (request.getAttribute("error") != null) { %>
<p style="color: red;"><%= request.getAttribute("error") %></p>
<% } %>
<form action="register" method="post">
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username" required><br>
    <label for="password">密码:</label>
    <input type="password" id="password" name="password" required><br>
    <label for="role">角色:</label>
    <select id="role" name="role">
        <option value="admin">管理员</option>
        <option value="warehouse">仓库管理员</option>
    </select><br>
    <input type="submit" value="注册">
</form>
<a href="login.jsp">已有账号?点击登录</a>
<%@ include file="footer.jsp" %>
/* styles.css */
body {
    font-family: "微软雅黑", sans-serif;
    background-color: #f4f4f4;
    margin: 0;
    padding: 0;
}

h1 {
    color: #333;
    text-align: center;
    margin-top: 20px;
}

form {
    background-color: #fff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    width: 300px;
    margin: 20px auto;
}

label {
    display: block;
    margin-bottom: 5px;
}

input[type="text"],
input[type="password"] {
    width: 100%;
    padding: 10px;
    margin-bottom: 15px;
    border: 1px solid #ccc;
    border-radius: 3px;
}

input[type="submit"] {
    background-color: #007BFF;
    color: #fff;
    padding: 10px 20px;
    border: none;
    border-radius: 3px;
    cursor: pointer;
}

input[type="submit"]:hover {
    background-color: #0056b3;
}

a {
    color: #007BFF;
    text-decoration: none;
}

a:hover {
    text-decoration: underline;
}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List, bean.Warehouse" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>仓库列表</title>
</head>
<body>
<h2>仓库列表</h2>
<a href="addWarehouse.jsp">新增仓库</a>
<table border="1">
    <tr>
        <th>仓库编号</th>
        <th>仓库名称</th>
        <th>仓库地址</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    <%
        List<Warehouse> warehouses = (List<Warehouse>) request.getAttribute("warehouses");
        if (warehouses != null) {
            for (Warehouse warehouse : warehouses) {
    %>
    <tr>
        <td><%= warehouse.getWarehouseId() %></td>
        <td><%= warehouse.getWarehouseName() %></td>
        <td><%= warehouse.getAddress() %></td>
        <td><%= warehouse.getRemark() %></td>
        <td>
            <a href="WarehouseServlet?action=edit&warehouseId=<%= warehouse.getWarehouseId() %>">编辑</a>
            <a href="WarehouseServlet?action=delete&warehouseId=<%= warehouse.getWarehouseId() %>">删除</a>
        </td>
    </tr>
    <%
            }
        }
    %>
</table>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List, bean.Warehouse" %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>仓库列表</title>
</head>
<body>
<h2>仓库列表</h2>
<table border="1">
    <tr>
        <th>仓库编号</th>
        <th>仓库名称</th>
        <th>仓库地址</th>
        <th>备注</th>
        <th>操作</th>
    </tr>
    <%
        List<Warehouse> warehouses = (List<Warehouse>) request.getAttribute("warehouses");
        if (warehouses != null) {
            for (Warehouse warehouse : warehouses) {
    %>
    <tr>
        <td><%= warehouse.getWarehouseId() %></td>
        <td><%= warehouse.getWarehouseName() %></td>
        <td><%= warehouse.getAddress() %></td>
        <td><%= warehouse.getRemark() %></td>
        <td>
            <!-- 修改操作 -->
            <a href="WarehouseServlet?action=edit&warehouseId=<%= warehouse.getWarehouseId() %>">修改</a>
            <!-- 删除操作 -->
            <a href="WarehouseServlet?action=delete&warehouseId=<%= warehouse.getWarehouseId() %>" onclick="return confirm('确定要删除该仓库吗?')">删除</a>
        </td>
    </tr>
    <%
            }
        }
    %>
</table>
</body>
</html>

8.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.stdu</groupId>
  <artifactId>111</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>111 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <kotlin.version>2.1.10</kotlin.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.26</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-core</artifactId>
      <version>9.0.97</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-stdlib-jdk8</artifactId>
      <version>${kotlin.version}</version>
    </dependency>
    <dependency>
      <groupId>org.jetbrains.kotlin</groupId>
      <artifactId>kotlin-test</artifactId>
      <version>${kotlin.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>111</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>

        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.4.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.3.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.13.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>3.3.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.4.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>3.1.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <plugins>
      <plugin>
        <groupId>org.jetbrains.kotlin</groupId>
        <artifactId>kotlin-maven-plugin</artifactId>
        <version>${kotlin.version}</version>
        <executions>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
            <configuration>
              <sourceDirs>
                <source>src/main/java</source>
                <source>target/generated-sources/annotations</source>
              </sourceDirs>
            </configuration>
          </execution>
          <execution>
            <id>test-compile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>test-compile</goal>
            </goals>
          </execution>
        </executions>
        <configuration>
          <jvmTarget>1.8</jvmTarget>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <executions>
          <execution>
            <id>default-compile</id>
            <phase>none</phase>
          </execution>
          <execution>
            <id>default-testCompile</id>
            <phase>none</phase>
          </execution>
          <execution>
            <id>compile</id>
            <phase>compile</phase>
            <goals>
              <goal>compile</goal>
            </goals>
          </execution>
          <execution>
            <id>testCompile</id>
            <phase>test-compile</phase>
            <goals>
              <goal>testCompile</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

最后,防止页面中出现乱码,加入以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <File name="FileAppender" fileName="logs/app.log" charset="UTF-8">
            <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="FileAppender"/>
        </Root>
    </Loggers>
</Configuration>

posted @   f-52Hertz  阅读(4)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示