You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JSP MVC项目插入MySQL数据时出现NullPointerException求助

排查并解决MVC Web项目中的数据库插入空指针异常

Hey there, let's dig into this NullPointerException you're hitting. From the error context and your code, the issue is definitely a null database connection causing the crash at line 27 in CustomerAddQuery.java (where you call con.prepareStatement(query)). Let's break down why this is happening and how to fix it.

为什么会出现空指针?

Your DBConnection.dbconnect() method returns null when it fails to establish a database connection (either from driver issues, wrong credentials, or a down MySQL server). Then in CustomerAddQuery, you try to call a method on this null connection object—boom, NullPointerException.

Let's list the most likely reasons the connection is failing:

  • Mismatched MySQL Driver: com.mysql.jdbc.Driver is for MySQL 5.x. If you're using MySQL 8.0+, you need com.mysql.cj.jdbc.Driver instead.
  • Missing Timezone Parameter: MySQL 8.0+ requires a timezone in the connection URL (e.g., serverTimezone=UTC), otherwise it throws a timezone error that kills the connection.
  • Incorrect Credentials: Your root password is set to an empty string—if your MySQL root account has a password, this will fail.
  • MySQL Server Not Running: If the MySQL service isn't started, the connection attempt will fail outright.

修复步骤

Step 1: Fix Database Connection Issues

First, ensure your database connection works correctly. Update DBConnection.java with these changes (adjust based on your MySQL version):

package dbhelpers;

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

public class DBConnection {
    public static Connection dbconnect() throws ClassNotFoundException, SQLException {
        Connection con = null;
        // Use com.mysql.jdbc.Driver if you're on MySQL 5.x
        Class.forName("com.mysql.cj.jdbc.Driver");
        // Add timezone parameter and correct your root password
        con = DriverManager.getConnection(
            "jdbc:mysql://localhost/vehicle_rental_system?useSSL=false&serverTimezone=UTC",
            "root",
            "your_actual_mysql_password"
        );
        return con;
    }
}

Step 2: Fix CustomerAddQuery to Handle Connections Properly

We'll fix how you call the static connection method, add null checks, and ensure resources are closed to avoid leaks:

package dbhelpers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import models.Customer;

public class CustomerAddQuery {

    public void addData(Customer customer) {
        String query = "insert into customers (`name`, `email`, `address`, `sex`, `bday`, `telephone` , `password`) values (?,?,?,?,?,?,?)";
        Connection con = null;
        PreparedStatement pst = null;

        try {
            // Call the static method directly (no need to instantiate DBConnection)
            con = DBConnection.dbconnect();
            if (con == null) {
                throw new SQLException("Failed to establish database connection");
            }

            pst = con.prepareStatement(query);
            pst.setString(1, customer.getName());
            pst.setString(2, customer.getEmail());
            pst.setString(3, customer.getAddress());
            pst.setString(4, customer.getSex());
            pst.setString(5, customer.getBday());
            pst.setString(6, customer.getTelephone());
            pst.setString(7, customer.getPassword());
            pst.execute();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            // Re-throw to let the controller handle the error
            throw new RuntimeException("Failed to save customer data", e);
        } finally {
            // Always close resources to prevent connection leaks
            try {
                if (pst != null) pst.close();
                if (con != null) con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

Step 3: Add Error Handling in the Servlet

Update your CustomerController to catch errors and notify the user instead of letting the server throw a 500:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Fetch form data
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    String address = request.getParameter("address");
    String sex = request.getParameter("sex");
    String bday = request.getParameter("bday");
    String tel = request.getParameter("tele");
    String password= request.getParameter("password");

    // Populate Customer object
    Customer customer = new Customer();
    customer.setName(name);
    customer.setEmail(email);
    customer.setAddress(address);
    customer.setSex(sex);
    customer.setBday(bday);
    customer.setTelephone(tel);
    customer.setPassword(password);

    CustomerAddQuery obj = new CustomerAddQuery();
    try {
        obj.addData(customer);
        request.setAttribute("successMessage", "Customer added successfully!");
    } catch (RuntimeException e) {
        request.setAttribute("errorMessage", "Failed to add customer: " + e.getMessage());
        e.printStackTrace();
    }

    // Forward back to index with status message
    String url = "/index.jsp";
    RequestDispatcher dispatcher = request.getRequestDispatcher(url);
    dispatcher.forward(request, response);
}

Step 4: Verify Prerequisites

  • Make sure your MySQL server is running (use net start mysql on Windows or sudo systemctl start mysql on Linux).
  • Ensure you have the correct MySQL driver JAR in your project's WEB-INF/lib folder (or add it as a Maven dependency if using Maven).

内容的提问来源于stack exchange,提问作者Kasun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:11:28