Java实现购物车功能:方式一:存放在session中.方式二:存储在数据库中

//将购物车产品加入到cookie中,方式同浏览记录。

Java实现购物车,方式一(简易版):存储在session中。这种方式实现还不严谨,大家看的时候看思路即可。

(1). JSP页面中,选择某一款产品,将产品id一并传递给Servlet进行接收。

```

<a href="<%=path %>/servlet/do_home_control?param=addShoppingCar&ep_>放入购物车</a>

```

(2). 在Servlet中接收用户传递的参数。

```

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String param = request.getParameter("param");

String path = request.getContextPath();

PrintWriter out = response.getWriter();

if ("addShoppingCar".equals(param)) {

String ep_id = request.getParameter("ep_id");

// 根据key值从session中获取map对象

Map<String, Easybuy_Product> shoppingCarMap = (Map<String, Easybuy_Product>) request

.getSession().getAttribute("shoppingCar");

// 首次创建

if (shoppingCarMap == null) {

shoppingCarMap = new HashMap<String, Easybuy_Product>();

}

if (!Tool.isNull(ep_id)) {

// 根据ep_id获得产品对象

Easybuy_Product ep = productService.getProductByEp_Id(Tool

.strToInt(ep_id));

// 判断map中是否存在此id

if (shoppingCarMap.containsKey(ep_id)) {

// 如果包含,则根据ep_id获得Easybuy_Product对象

Easybuy_Product easybuy_Product = shoppingCarMap.get(ep_id);

easybuy_Product.setEp_sum(easybuy_Product.getEp_sum() + 1);

shoppingCarMap.put(ep_id, easybuy_Product);

} else {

ep.setEp_sum(1);

shoppingCarMap.put(ep_id, ep);

}

// 将session写回去

request.getSession()

.setAttribute("shoppingCar", shoppingCarMap);

}

response.sendRedirect(request.getContextPath() + "/shopping.jsp");

}

```

其中,Tool类中写了一个公共方法isNull,用来判断变量是否为null

```

/**

* 非空验证

*

* @param args

*/

public static boolean isNull(String pageString) {

if (pageString == null || "".equals(pageString)) {

return true;

} else {

return false;

}

}

```

Java实现购物车,方式二:根据用户的登录状态,如果用户没有登录,则用户加入到购物车中的产品,存储到session中;如果用户登录,则将用户购物车中的产品存储到数据库中或者从数据库中读取数据显示购物车列表。

具体实现如下:

(1). JSP页面中,选择某一款产品,将产品id一并传递给Servlet进行接收。

```

<a href="<%=path %>/servlet/do_home_control?>放入购物车</a>

```

(2). 在Servlet中,接收产品ID.

```

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html;charset=utf-8");

request.setCharacterEncoding("utf-8");

ProductService ps = new ProductServiceImpl();

PrintWriter out = response.getWriter();

String path=request.getContextPath();

String a = request.getParameter("id");

int id = 0;

//如果a==null,说明用户直接点击购物车超链接进入此页面;否则用户通过选择产品,将此产品加入到购物车

if(a!=null){

id=Integer.parseInt(a);

}

String price=request.getParameter("price");

//判断用户是否登录

User user = (User) request.getSession().getAttribute("userName");

if(user==null){

//说明用户没有登录,也是允许用户加入购物车的。此时购物车信息存放到session里面

Map<Integer,Product> myCart = (Map<Integer, Product>) request.getSession().getAttribute("MyCart");

if(id != 0){

//根据产品id获得产品

Product product = ps.getById(id);

if(myCart == null){

//说明是第一次加入购物车

myCart = new HashMap<Integer, Product>();

myCart.put(id, product);

}else{

if(myCart.containsKey(id)){

//如果购物车中存在此商品id,则商品数量加1

Product product1 = myCart.get(id);

product1.setCount(product1.getCount()+1);

myCart.put(id, product1);

}else{

myCart.put(id, product);

}

}

}

request.getSession().setAttribute("MyCart", myCart);

request.getSession().setMaxInactiveInterval(10*60);

}else{

Map<Integer,Product> myCart = (Map<Integer, Product>) request.getSession().getAttribute("MyCart");

if(myCart == null){

if(id != 0){

//根据产品ID获取一条购物车信息

Shopping shoppingItem = sService.getShoppingItemByEp_ID(id);

if(shoppingItem == null){

//如果不存在,则第一次加入此产品 insert

sService.insert(id,price,1,user.getEu_user_id());

}else{

shoppingItem.setEod_quantity(shoppingItem.getEod_quantity()+1);

//更新

sService.updateShoppingItem(shoppingItem);

}

}

}else{

//便利session

Set<Integer> keys = myCart.keySet();

Iterator<Integer> iterator = keys.iterator();

while (iterator.hasNext()) {

Product p = myCart.get(iterator.next());

//根据用户名和产品id判断此产品是否存在;如果存在,更新数量,如果不存在,则插入

if(sService.isExistByUser_EpId(user.getEu_user_id(),p.getEp_id())){

Shopping shoppingItem = sService.getShoppingItemByEp_ID(p.getEp_id());

if(p.getEp_id() == id){

p.setCount(p.getCount()+1);

}

shoppingItem.setEod_quantity(shoppingItem.getEod_quantity()+p.getCount());

sService.updateShoppingItem(shoppingItem);

}else{

sService.insert(id,price,p.getCount(),user.getEu_user_id());

}

}

request.getSession().removeAttribute("MyCart");

}

//最后往前台返回的是一个购物车产品列表

List<Shopping> shoppings = sService.getShoppintCartByUserId(user.getEu_user_id());

request.getSession().setAttribute("shoppings",shoppings);

}

out.print("<script type='text/javascript'>location='"

+path

+ "/shopping.jsp';</script>");

}

```

(3). 在JSP页面中显示购物车列表

```

<table>

<tr>

<th>商品名称</th>

<th>商品价格</th>

<th>购买数量</th>

<th>操作</th>

</tr>

<c:choose>

<c:when test="${userName==null }">

<c:choose>

<c:when test="${MyCart==null||MyCart.size()==0 }">

您还未添加商品到购物车!

</c:when>

<c:otherwise>

<c:forEach items="${MyCart}" var="cart">

<tr >删除</a>

</td>

</tr>

</c:forEach>

</c:otherwise>

</c:choose>

</c:otherwise>

</c:choose>

</table>

```

我个人认为方式二更好一些,也更贴近生活中用的淘宝功能。

以上功能,时间有些紧迫,有不足之处欢迎大家指正。

谢谢你来看我。