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

Servlet中doPost()的用法:从JSP取参插入数据库并传至Servlet

Alright, let's walk through how to get parameters from a JSP, insert them into a database using Java, and handle the entire flow with a Servlet. Here's a complete, practical implementation tailored to your setup:


1. JSP Form (Collect User Input)

First, create a JSP page with a form that sends data to your Servlet. The action should match the @WebServlet mapping you've defined, and we'll use POST for secure data transmission:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Create Project</title>
</head>
<body>
    <h2>Create New Project</h2>
    <form action="projectForm" method="post">
        <label for="projectName">Project Name:</label>
        <input type="text" id="projectName" name="projectName" required><br><br>
        
        <label for="projectDesc">Project Description:</label>
        <textarea id="projectDesc" name="projectDesc" required></textarea><br><br>
        
        <input type="submit" value="Create Project">
    </form>
</body>
</html>

2. Servlet Class (CreateProject.java)

This Servlet will handle the form submission, extract parameters from the request, and call your database connection class to insert the data. We'll use doPost since our form uses the POST method:

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("/projectForm")
public class CreateProject extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Extract parameters from the JSP form
        String projectName = request.getParameter("projectName");
        String projectDesc = request.getParameter("projectDesc");

        // Call DBConnection to insert the project data
        boolean isInserted = DBConnection.insertProject(projectName, projectDesc);

        // Redirect to appropriate page based on insertion result
        if (isInserted) {
            response.sendRedirect("success.jsp"); // Create a success page to confirm completion
        } else {
            response.sendRedirect("error.jsp"); // Create an error page to handle failures
        }
    }
}

3. Database Connection Class (DBConnection.java)

This class manages the database connection and executes the insert query. Always use PreparedStatement to prevent SQL injection, and leverage try-with-resources to automatically close connections/streams (avoids resource leaks):

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

public class DBConnection {
    // Database credentials (move these to a config file in production for security)
    private static final String DB_URL = "jdbc:mysql://localhost:3306/your_database_name";
    private static final String DB_USER = "your_db_username";
    private static final String DB_PASSWORD = "your_db_password";

    public static boolean insertProject(String projectName, String projectDesc) {
        String insertQuery = "INSERT INTO projects (name, description) VALUES (?, ?)";

        // Try-with-resources auto-closes Connection and PreparedStatement
        try (Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
             PreparedStatement pstmt = conn.prepareStatement(insertQuery)) {

            // Set values for the prepared statement parameters
            pstmt.setString(1, projectName);
            pstmt.setString(2, projectDesc);

            // Execute the insert query and check if rows were affected
            int rowsAffected = pstmt.executeUpdate();
            return rowsAffected > 0; // Return true if insertion succeeded

        } catch (SQLException e) {
            e.printStackTrace(); // Replace with a logging framework (like SLF4J) in production
            return false;
        }
    }
}

4. Key Best Practices to Follow
  • Avoid Hardcoding Credentials: Store database URL, username, and password in a properties file instead of embedding them in DBConnection.java—this makes updates easier and more secure.
  • Validate Input: Add server-side validation in the Servlet (e.g., check if project name isn't empty, doesn't contain invalid characters) before sending data to the database.
  • Handle Exceptions Gracefully: Instead of printing stack traces, use a logging framework to record errors in production—this helps with debugging without exposing sensitive info to users.
  • Use Connection Pools: For larger applications, use a connection pool (like HikariCP) instead of creating a new connection for every request—it improves performance and resource management.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:00:11