如何能够实现购物车原理?
//BuyGoodsServlet.java /* 实现购物车原理的例子!*/
import java.io.*;
import java.util.zip.*;
import javax.servlet.*;
import javax.servlet.http.*;
/*
在会话跟踪(2)的视频中,这个类实现购物车!
*/
public class BuyGoodsServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession();
ArrayList previousItems =(ArrayList)session.getAttribute("previousItems");
if(previousItems == null)
{
previousItems = new ArrayList();
session.setAttribute("previousItems",previousItems);
}
String newItem = request.getParameter("newItem"); //新的购物东西(参数);
response.setContentType("text/html;charset=gbk");
PrintWriter out = response.getWriter();
out.println("<html><body>");
synchronized(previousItems) { //同一用户不能同时,并发同时加入两个购物产品 if(newItem != null)
{
previousItems.add(newItem); //加入购物车!
}
if(previousItems.size()==0)
{
out.println("<T>No items</T>"); //没有购物
}
else
{ //把所有购物的内容,用列表显示出来!
out.println("<UL>"); //列表元素
for(int i=0;i<previousItems.size();i++)
{
out.println("<LI>"+(String)previousItems.get(i));
}
out.println("<UL>");
}//if
}
out.println("</body></html>");
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, java.io.IOException {
doGet(request,response);
}
}
本文地址:http://www.45fan.com/dnjc/68064.html