fix<商品加购>

master
liyansheng 2024-12-21 16:04:38 +08:00
parent eb29d0c258
commit 42923c1a6a
5 changed files with 28 additions and 7 deletions

View File

@ -1,6 +1,7 @@
package example.controller;
import example.model.Computer;
import example.model.User;
import example.service.ICartService;
import example.service.impl.CartServiceImpl;
@ -29,9 +30,11 @@ public class CartServlet extends HttpServlet {
}
break;
case "add":
String id = req.getParameter("id");
req.getSession().setAttribute("cart",id);
resp.sendRedirect("/cart");
try {
addCart(req,resp);
} catch (Exception e) {
throw new RuntimeException(e);
}
break;
case "remove":
String removeId = req.getParameter("id");
@ -44,8 +47,17 @@ public class CartServlet extends HttpServlet {
}
}
private void addCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
String id = req.getParameter("id");
User user = (User) req.getSession().getAttribute("user");
cartService.addCart(Integer.parseInt(id),user.getId());
req.setAttribute("msg","加购成功");
req.getRequestDispatcher("/computerList").forward(req,resp);
}
private void toCart(HttpServletRequest req, HttpServletResponse resp) throws Exception {
List<Computer> computers = cartService.myCart(16);
User user = (User) req.getSession().getAttribute("user");
List<Computer> computers = cartService.myCart(user.getId());
req.setAttribute("computers",computers);
req.getRequestDispatcher("cart.jsp").forward(req,resp);
}

View File

@ -39,7 +39,6 @@ public class UserServlet extends HttpServlet {
req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req, resp);
break;
}
super.doGet(req, resp);
}
private void getUserList(HttpServletRequest req, HttpServletResponse resp) throws Exception {

View File

@ -6,4 +6,6 @@ import java.util.List;
public interface ICartService {
List<Computer> myCart(Integer userId) throws Exception;
void addCart(int i, int id) throws Exception;
}

View File

@ -4,7 +4,6 @@ import example.dao.CartDao;
import example.model.Computer;
import example.service.ICartService;
import java.util.Collections;
import java.util.List;
public class CartServiceImpl implements ICartService {
@ -15,4 +14,9 @@ public class CartServiceImpl implements ICartService {
public List<Computer> myCart(Integer userId) throws Exception {
return cartDao.getCart(userId);
}
@Override
public void addCart(int productId, int userId) throws Exception {
cartDao.addCart(userId, productId);
}
}

View File

@ -28,12 +28,16 @@
<td>${computer.stock}</td>
<td>
<a href="/editComputer?id=${computer.id}">Edit</a> |
<a href="/deleteComputer?id=${computer.id}">Delete</a>
<a href="/deleteComputer?id=${computer.id}">Delete</a> |
<a href="/cart?action=add&id=${computer.id}">加购</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<hr>
<p style="color: red;">${requestScope.msg}</p>
<a href="/cart?action=list">我的购物车</a>
<br/>
<a href="/addComputer">Add New Computer</a>
<br>