本項(xiàng)目是一個(gè)基于JSP和MySQL的購物車網(wǎng)站。主要功能包括瀏覽商品、加入購物車、結(jié)算等。以下是部分代碼實(shí)現(xiàn):
<%@ page import="java.sql.*"%> <%@ page import="java.util.*"%> <% String product_id = request.getParameter("product_id"); String quantity = request.getParameter("quantity"); ResultSet rs = null; Statement st = null; Connection con = null; if (session.getAttribute("cart") == null) { Map<String, Integer> cart = new HashMap<String, Integer>(); cart.put(product_id, Integer.parseInt(quantity)); session.setAttribute("cart", cart); } else { Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart"); if (cart.containsKey(product_id)) { cart.put(product_id, cart.get(product_id) + Integer.parseInt(quantity)); } else { cart.put(product_id, Integer.parseInt(quantity)); } session.setAttribute("cart", cart); } %>
以上代碼實(shí)現(xiàn)加入購物車的功能。通過傳遞商品ID和數(shù)量,將對應(yīng)的購物車數(shù)據(jù)存儲在session中。下面是結(jié)算頁面的數(shù)據(jù)庫查詢實(shí)現(xiàn):
<table> <% double totalPrice = 0.0; if (session.getAttribute("cart") != null) { Map<String, Integer> cart = (Map<String, Integer>) session.getAttribute("cart"); Set<String> ids = cart.keySet(); if (ids.size() >0) { String sql ="SELECT * FROM products WHERE product_id IN ("; for (String id : ids) { sql += id + ","; } sql = sql.substring(0, sql.length() - 1) + ")"; try { con = DriverManager.getConnection(url, user, password); st = con.createStatement(); rs = st.executeQuery(sql); while (rs.next()) { int quantity = cart.get(rs.getString("product_id")); double price = rs.getDouble("price"); out.println("<tr>"); out.println("<td>" + rs.getString("product_name") + "</td>"); out.println("<td>" + quantity + "</td>"); out.println("<td>$" + price + "</td>"); double total = quantity * price; totalPrice += total; out.println("<td>$" + total + "</td>"); out.println("</tr>"); } } catch (SQLException e) { out.println("Error: " + e.getMessage()); } finally { try { if (rs != null) { rs.close(); } if (st != null) { st.close(); } if (con != null) { con.close(); } } catch (SQLException e) { out.println("Error: " + e.getMessage()); } } } } %> <tr> <td colspan="3"></td> <td><b>Total: $<%= totalPrice %></b></td> </tr> </table>
以上代碼通過查詢購物車中的商品ID對應(yīng)的產(chǎn)品信息,計(jì)算購物車中所有商品的總價(jià),最后輸出到頁面中。同時(shí),需要注意數(shù)據(jù)庫連接的釋放操作,以免出現(xiàn)資源泄露。