Servlet+JDBC实战开发书店项目讲解第二篇:商品管理实现

当你开始进行servlet+jdbc书店系统的实战开发时,商品管理功能是一个重要的模块。在这篇博客中,我将向你展示详细的步骤,并提供代码示例来帮助你完成这个功能。

步骤1: 设计JDBC类

首先,我们需要创建一个JDBC类来实现与数据库的连接和操作。你可以使用Java的JDBC API来完成这个任务。以下是一个简单的JDBC类示例,你可以根据自己的需求进行修改:

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

public class JDBCUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/bookstore";
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";

    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void closeConnection(Connection connection) {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

你需要将上述代码中的URLUSERNAMEPASSWORD修改为你自己的数据库连接信息。

步骤2: 设计商品列表页面

接下来,我们将设计一个展示商品列表的页面。你可以使用HTML和CSS来创建该页面。以下是一个简单的示例:

DOCTYPE html>
<html>
<head>
    <title>商品列表title>
    <style>
        table {
            border-collapse: collapse;
        }
        th, td {
            border: 1px solid black;
            padding: 5px;
        }
    style>
head>
<body>
    <h1>商品列表h1>
    <table>
        <tr>
            <th>商品IDth>
            <th>商品名称th>
            <th>价格th>
        tr>
        
    table>
body>
html>

你可以根据需要自定义商品列表的样式和布局。

步骤3: 设计商品增加页面

接下来,我们将设计一个用于添加商品的页面。这个页面通常包含一些输入字段,用户可以在这些字段中输入商品的信息。以下是一个简单的示例:

DOCTYPE html>
<html>
<head>
    <title>添加商品title>
head>
<body>
    <h1>添加商品h1>
    <form action="AddProductServlet" method="post">
        <label for="name">商品名称:label><br>
        <input type="text" id="name" name="name" required><br>
        <label for="price">价格:label><br>
        <input type="text" id="price" name="price" required><br>
        <input type="submit" value="添加">
    form>
body>
html>

你可以根据需要添加更多的输入字段。

步骤4: 设计商品修改页面

接下来,我们将设计一个用于修改商品的页面。这个页面通常包含一些输入字段,用户可以在这些字段中修改商品的信息。以下是一个简单的示例:

DOCTYPE html>
<html>
<head>
    <title>修改商品title>
head>
<body>
    <h1>修改商品h1>
    <form action="UpdateProductServlet" method="post">
        <input type="hidden" name="id" value="商品的ID">
        <label for="name">商品名称:label><br>
        <input type="text" id="name" name="name" required><br>
        <label for="price">价格:label><br>
        <input type="text" id="price" name="price" required><br>
        <input type="submit" value="保存">
    form>
body>
html>

请注意在上面的示例中,我们添加了一个隐藏字段来保存商品的ID。

步骤5: 设计控制器(Controller)

下一步是设计用于处理各种操作的控制器。控制器非常抱歉,由于文本长度限制,我的回答被截断了。以下是步骤5到步骤7的内容:

步骤5: 设计控制器(Controller)

下一步是设计用于处理各种操作的控制器。控制器是一个Java类,负责接收用户请求,调用相应的DAO类来处理数据库操作,并返回结果给用户。以下是一个简单的示例:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

public class ProductController extends HttpServlet {
    private ProductDAO productDAO;

    public void init() {
        productDAO = new ProductDAO();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();

        switch (action) {
            case "/list":
                listProducts(request, response);
                break;
            case "/add":
                showAddForm(request, response);
                break;
            case "/edit":
                showEditForm(request, response);
                break;
            case "/update":
                updateProduct(request, response);
                break;
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    private void listProducts(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Product> products = productDAO.getAllProducts();
        request.setAttribute("products", products);
        RequestDispatcher dispatcher = request.getRequestDispatcher("product-list.jsp");
        dispatcher.forward(request, response);
    }

    private void showAddForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = request.getRequestDispatcher("add-product.jsp");
        dispatcher.forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Product product = productDAO.getProductById(id);
        request.setAttribute("product", product);
        RequestDispatcher dispatcher = request.getRequestDispatcher("edit-product.jsp");
        dispatcher.forward(request, response);
    }

    private void updateProduct(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        double price = Double.parseDouble(request.getParameter("price"));
        Product product = new Product(id, name, price);
        productDAO.updateProduct(product);
        response.sendRedirect("list");
    }
}

在上述示例中,你需要根据自己的需求修改代码,确保与你的DAO类和页面文件名对应。

步骤6: 设计DAO类

DAO类负责与数据库进行交互,并执行CRUD操作(增加、查询、更新、删除)。以下是一个简单的示例:

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class ProductDAO {
    private static final String SELECT_ALL_PRODUCTS = "SELECT * FROM products";
    private static final String SELECT_PRODUCT_BY_ID = "SELECT * FROM products WHERE id = ?";
    private static final String INSERT_PRODUCT = "INSERT INTO products (name, price) VALUES (?, ?)";
    private static final String UPDATE_PRODUCT = "UPDATE products SET name = ?, price = ? WHERE id = ?";

    public List<Product> getAllProducts() {
        List<Product> products = new ArrayList<>();
        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(SELECT_ALL_PRODUCTS)) {
            ResultSet resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String name = resultSet.getString("name");
                double price = resultSet.getDouble("price");

                Product product = new Product(id, name, price);
                products.add(product);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return products;
    }

    public Product getProductById(int id) {
        Product product = null;
        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(SELECT_PRODUCT_BY_ID)) {
            statement.setInt(1, id);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                String name = resultSet.getString("name");
                double price = resultSet.getDouble("price");

                product = new Product(id, name, price);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return product;
    }

    public void addProduct(Product product) {
        try (Connection connection = JDBCUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(INSERT_PRODUCT)) {
            statement.setString(1, product.getName());
            statement.setDouble(2, product.getPrice());
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateProduct(Product product) {
        try (Connection connection =public void updateProduct(Product product) {
try (Connection connection = JDBCUtil.getConnection();
PreparedStatement statement = connection.prepareStatement(UPDATE_PRODUCT)) {
statement.setString(1, product.getName());
statement.setDouble(2, product.getPrice());
statement.setInt(3, product.getId());
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}

}

写到这里,应该这功能算是能实现了,当然页面上需要加点jstl的支持,这个留给同学们完成,有问题叫我

你可能感兴趣的:(java,servlet)