Jsp下单后商品变化功能代码
时间: 2024-03-17 11:44:11 浏览: 12
假设您的JSP页面上有一个表单,用户可以在该表单中选择要购买的商品和数量,并单击“提交订单”按钮。在提交订单后,您需要更新商品库存信息。
以下是一个示例JSP页面,其中包含一个表单,用户可以选择要购买的商品和数量:
```html
<html>
<head>
<title>下单页面</title>
</head>
<body>
<h1>请选择您要购买的商品</h1>
<form action="placeOrder.jsp" method="post">
<label for="item1">商品1</label>
<input type="checkbox" name="item1" value="1">
<br>
<label for="item2">商品2</label>
<input type="checkbox" name="item2" value="1">
<br>
<label for="item3">商品3</label>
<input type="checkbox" name="item3" value="1">
<br>
<label for="quantity">数量</label>
<input type="text" name="quantity">
<br>
<input type="submit" value="提交订单">
</form>
</body>
</html>
```
在用户提交订单后,将会调用placeOrder.jsp页面来处理订单。下面是一个示例placeOrder.jsp页面的代码,该代码将更新商品库存信息:
```jsp
<%@ page language="java" %>
<%@ page import="java.sql.*" %>
<html>
<head>
<title>下单结果</title>
</head>
<body>
<h1>下单结果</h1>
<%
// 获取表单提交的数据
String item1 = request.getParameter("item1");
String item2 = request.getParameter("item2");
String item3 = request.getParameter("item3");
String quantity = request.getParameter("quantity");
// 更新库存信息
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "username", "password");
// 更新商品1库存
if (item1 != null && item1.equals("1")) {
stmt = conn.prepareStatement("UPDATE items SET stock = stock - ? WHERE id = 1");
stmt.setInt(1, Integer.parseInt(quantity));
stmt.executeUpdate();
}
// 更新商品2库存
if (item2 != null && item2.equals("1")) {
stmt = conn.prepareStatement("UPDATE items SET stock = stock - ? WHERE id = 2");
stmt.setInt(1, Integer.parseInt(quantity));
stmt.executeUpdate();
}
// 更新商品3库存
if (item3 != null && item3.equals("1")) {
stmt = conn.prepareStatement("UPDATE items SET stock = stock - ? WHERE id = 3");
stmt.setInt(1, Integer.parseInt(quantity));
stmt.executeUpdate();
}
// 提交事务
conn.commit();
} catch (Exception e) {
// 回滚事务
conn.rollback();
out.println("下单失败:" + e.getMessage());
} finally {
// 关闭连接
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
%>
<p>下单成功!</p>
</body>
</html>
```
在placeOrder.jsp页面中,首先获取表单提交的数据(包括商品选择和数量)。然后,使用Java JDBC API连接到数据库,并根据用户的选择更新相应的商品库存。最后,如果所有操作都成功,则提交事务。如果发生任何错误,则会回滚事务并向用户显示错误消息。