烟台网站建设中越来越多的朋友开始选择java技术实现自己的网站,oa,商城,做商城必须考虑的一个技术点就是购物车的实现,有人选择字符串截取方式,然后记录入session ,有人选择java的类 用对类的元素的增删读改实现购物车物品的维护,下面为大家带来一种不同的方式:hashmap购物车
购物车代码(Servlet处理段):
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
//声明会话对象
HttpSession session = request.getSession();
//接收超链接传过来的参数
String foodId = request.getParameter("foodId");
//为了避免覆盖,先获得购物车对象
HashMap cart = (HashMap)session.getAttribute("cart");
//如果购物车不存在,则创建购物车
if (cart == null) {
cart = new HashMap();
//将购物车存入会话中
session.setAttribute("cart", cart);
}
//判断商品是否在购物车中
if (cart.get(foodId) == null) {
//如果不在,创建一个条目到购物车中
cart.put(foodId, 1);
} else {
//如果在,更新其数量
int num = Integer.parseInt(cart.get(foodId).toString())+1;
cart.put(foodId, num);
}
//在此将购物车保存到会话中
session.setAttribute("cart", cart);
//跳转页面
response.sendRedirect("/RestaurantSys/shopCart.jsp");
out.flush();
out.close();
}
记住:其中,foodId为超链接传过来的参数。
大家在参看购物车的jsp中,写如下代码:
<%!double total = 0; %>
<%
HashMap cart = (HashMap)session.getAttribute("cart");
Object[] isbn = cart.keySet().toArray();
for (int i = 0; i < isbn.length; i++) {
DBOperate dbo = new DBOperate();
dbo.getCon();
FoodBean fBean = (FoodBean)dbo.searchFoodInfo(isbn[i].toString());
int num = Integer.parseInt(cart.get(isbn[i]).toString());
double price = fBean.getFoodPrice();
double sum = price * num;
total += sum;
%>
<tr>
<td><div align="center" class="STYLE1"><%=isbn[i] %></div></td>
<td><div align="center" class="STYLE1"><%=fBean.getFoodName() %></div></td>
<td><div align="center" class="STYLE1">¥<%=new DecimalFormat("0.00").format(price) %></div></td>
<td><div align="center" class="STYLE1"><%=num %></div></td>
<td><div align="center" class="STYLE1">¥<%=new DecimalFormat("0.00").format(sum) %></div></td>
</tr>
<%} %>
好啦,代码分享完毕,欢迎大家访问我的网站有技术问题 可以相互交流http://www.gongyingwl.com/