JSP 頁面接收表單提交,通過 JDBC 將數據插入數據庫是 Java Web 開發的基礎技能。本文提供從表單設計、參數接收、數據庫連接到預編譯語句防注入的完整最佳實踐代碼。
用戶填寫表單 → form 提交 (POST) → JSP/Servlet 接收參數
→ 驗證數據 → 建立數據庫連接 → PreparedStatement 預編譯 SQL
→ 綁定參數 → 執行更新 → 關閉資源 → 响應結果
<%@ page contentType="text/html;charset=UTF-8" %>
<form action="save.jsp" method="post">
國家: <input name="country"><br>
專業: <input name="profession"><br>
班級: <input name="classes"><br>
學號: <input name="studentId"><br>
姓名: <input name="name"><br>
聯系方式: <input name="contact"><br>
開始日期: <input name="startdate" type="date"><br>
結束日期: <input name="enddate" type="date"><br>
老師: <input name="teacher"><br>
<input type="submit" value="提交">
</form>
<%@ page import="java.sql.*, javax.sql.DataSource" %>
<%@ page import="javax.naming.InitialContext" %>
<%
// 1. 獲取參數
String country = request.getParameter("country");
String profession = request.getParameter("profession");
String classes = request.getParameter("classes");
String studentId = request.getParameter("studentId");
String name = request.getParameter("name");
String contact = request.getParameter("contact");
String startdate = request.getParameter("startdate");
String enddate = request.getParameter("enddate");
String teacher = request.getParameter("teacher");
// 2. 基礎校驗
if (name == null || name.trim().isEmpty()) {
out.println("姓名不能為空");
return;
}
Connection conn = null;
PreparedStatement ps = null;
try {
// 3. 獲取連接 (推薦使用數據源/連接池)
InitialContext ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/MyDB");
conn = ds.getConnection();
// 4. 預編譯 SQL - 防止 SQL 注入!
String sql = "INSERT INTO LeaveList " +
"(country, profession, classes, studentId, name, contact, startdate, enddate, teacher) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
ps = conn.prepareStatement(sql);
ps.setString(1, country);
ps.setString(2, profession);
ps.setString(3, classes);
ps.setString(4, studentId);
ps.setString(5, name);
ps.setString(6, contact);
ps.setString(7, startdate);
ps.setString(8, enddate);
ps.setString(9, teacher);
// 5. 執行
int rows = ps.executeUpdate();
if (rows > 0) {
out.println("保存成功!<a href='form.jsp'>繼續添加</a>");
} else {
out.println("保存失敗,請重試");
}
} catch (Exception e) {
e.printStackTrace();
out.println("系統錯誤:" + e.getMessage());
} finally {
// 6. 關閉資源 (逆序)
try { if (ps != null) ps.close(); } catch (Exception ignore) {}
try { if (conn != null) conn.close(); } catch (Exception ignore) {}
}
%>
| 項目 | 錯誤做法 | 正確做法 |
|---|---|---|
| SQL 拼接 | "VALUES ('"+name+"')" | PreparedStatement + ? 佔位符 |
| 連接管理 | 每請求 new Connection() | 配置 DataSource (Druid/HikariCP) + JNDI |
| 異常處理 | 吞掉異常或僅 printStackTrace | 記錄日誌 + 友好提示 + 事務回滾 |
| 編碼 | 忽略字符集 | DB/連接/頁面統一 UTF-8 |
| 架構 | JSP 混寫業務邏輯 | Servlet/Controller 處理業務,JSP 僅渲染 |
// LeaveServlet.java
@WebServlet("/leave/save")
public class LeaveServlet extends HttpServlet {
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 接收參數、調用 Service、轉發到結果頁
LeaveService service = new LeaveService();
boolean ok = service.save(leave);
req.setAttribute("success", ok);
req.getRequestDispatcher("/leave/result.jsp").forward(req, resp);
}
}