Servlet+JSP通过按钮实现商品增加与减少
时间: 2023-11-22 22:53:40 浏览: 38
首先,在 JSP 页面上创建两个按钮,一个用于增加商品数量,一个用于减少商品数量,例如:
```html
<form action="updateQuantityServlet" method="post">
<input type="hidden" name="productId" value="${productId}">
<input type="submit" name="quantityChange" value="+" />
<input type="submit" name="quantityChange" value="-" />
</form>
```
其中,`productId` 是要修改数量的商品的 ID。`quantityChange` 是按钮的名称,用于区分用户点击的是增加还是减少按钮。
接下来,在 Servlet 中处理按钮的点击事件,并更新商品数量:
```java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int productId = Integer.parseInt(request.getParameter("productId"));
String quantityChange = request.getParameter("quantityChange");
int quantity = 0;
// 获取当前商品数量
// ...
if (quantityChange.equals("+")) {
quantity++; // 增加数量
} else if (quantityChange.equals("-")) {
quantity--; // 减少数量
}
// 更新商品数量
// ...
// 重定向回商品详情页面
response.sendRedirect("productDetail.jsp?productId=" + productId);
}
```
这里假设已经实现了获取当前商品数量和更新商品数量的代码。注意,在更新商品数量之后,要使用 `response.sendRedirect` 方法将用户重定向回商品详情页面,以便用户能够看到更新后的商品数量。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)