早期 JSP 開發常直接在頁面嵌入 JDBC 程式碼執行 SQL,雖然直觀但存在嚴重的安全性與維護性問題。本文將展示典型的「JSP + SQL 混寫」增刪改查範例,並深度剖析其缺陷,引導開發者邁向現代化分層架構。
<%@ page import="java.sql.*" %>
<%
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root", pwd = "123456";
Connection con = DriverManager.getConnection(url, user, pwd);
Statement stmt = con.createStatement();
%>
<%
String sql = "INSERT INTO allorder VALUES ('" + orderId + "','"
+ bookId + "','" + amount + "','" + userName + "')";
int result = stmt.executeUpdate(sql);
if (result == 1) response.sendRedirect("index.jsp");
else response.sendRedirect("detail.jsp");
%>
<%
String sql = "DELETE FROM allorder WHERE id='" + orderId + "'";
int result = stmt.executeUpdate(sql);
if (result == 1) response.sendRedirect("index.jsp");
else out.println("shopCar.jsp");
%>
<table>
<%
ResultSet rs = stmt.executeQuery("SELECT * FROM allorder");
while (rs.next()) {
String amount = rs.getString("amount");
String orderId = rs.getString("id");
String bookName = rs.getString("name");
String price = rs.getString("price");
String picture = rs.getString("pic");
%>
<tr>
<td><%=orderId%></td>
<td><%=picture%></td>
<td><%=bookName%></td>
<td><%=price%></td>
<td><%=amount%></td>
<td>
<input type="button" value="刪除"
onclick="location.href='delete.jsp?orderId=<%=orderId%>'">
</td>
</tr>
<% } %>
</table>
字串拼接構建 SQL 允許攻擊者輸入 ' OR '1'='1 繞過驗證或刪除資料表。絕對禁止在生產環境使用此方式。
範例中 ResultSet、Statement、Connection 僅在正常流程關閉,異常拋出時將導致連線池耗盡。
JSP 應專注於呈現,資料存取層應獨立為 DAO/Service,便於單元測試與複用。
多條 SQL 操作無法保證原子性,易產生髒資料。
String sql = "INSERT INTO allorder VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, orderId);
ps.setString(2, bookId);
ps.setInt(3, amount);
ps.setString(4, userName);
ps.executeUpdate();
<!-- context.xml -->
<Resource name="jdbc/mydb" auth="Container" type="javax.sql.DataSource"
maxTotal="20" maxIdle="5" maxWaitMillis="10000"
username="root" password="123456"
driverClassName="com.mysql.cj.jdbc.Driver"
url="jdbc:mysql://localhost:3306/mydb"/>
// JSP/Servlet 中獲取
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/mydb");
Connection con = ds.getConnection();
<c:forEach items="${orderList}" var="order">
<tr>
<td>${order.id}</td>
<td>${order.bookName}</td>
<td>${order.price}</td>
<td><a href="delete?id=${order.id}">刪除</a></td>
</tr>
</c:forEach>
「JSP 混寫 SQL」僅適合快速原型驗證或教學示範。正式專案務必採用 連線池 + PreparedStatement + 分層架構 + 交易管理,並配合參數化查詢徹底杜絕 SQL 注入。建議學習 Spring Boot + MyBatis/JPA 現代化技術棧,從根本上解決上述問題。