servlet+jsp通过a标签实现商品的增加与减少
时间: 2023-11-27 18:53:30 浏览: 38
可以通过在a标签中设置href属性和onclick事件来实现商品的增加与减少。
首先,在jsp页面中,可以设置两个a标签,一个用于增加商品数量,一个用于减少商品数量。例如:
```
<a href="#" onclick="add()">增加</a>
<a href="#" onclick="reduce()">减少</a>
```
其中,add()和reduce()分别是JavaScript函数,用于实现增加和减少商品数量的功能。
然后,在JavaScript中,可以通过AJAX技术向servlet发送请求,实现商品数量的增加和减少。例如:
```
function add() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "addGoodsServlet?goodsId=xxx", true);
xhr.send();
}
function reduce() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "reduceGoodsServlet?goodsId=xxx", true);
xhr.send();
}
```
其中,addGoodsServlet和reduceGoodsServlet是servlet的名称,goodsId是要增加或减少的商品的ID号。
最后,在servlet中,可以根据请求的参数,修改数据库中商品的数量。例如:
```
public class AddGoodsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String goodsId = request.getParameter("goodsId");
// 根据商品ID号,从数据库中查询商品数量
int goodsNum = ...;
// 增加商品数量
goodsNum++;
// 更新数据库中商品数量
...
// 返回响应结果
response.getWriter().write("success");
}
}
public class ReduceGoodsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String goodsId = request.getParameter("goodsId");
// 根据商品ID号,从数据库中查询商品数量
int goodsNum = ...;
// 减少商品数量
goodsNum--;
// 更新数据库中商品数量
...
// 返回响应结果
response.getWriter().write("success");
}
}
```
这样,就可以通过a标签实现商品的增加与减少了。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)