ajax 实现购物车的实例
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/script/jquery-1.12.4.min.js"></script>
<script type="text/javascript"> var obj={'bookName':'Oracle','totalBookNumber':3,'totalMoney':300}; alert(obj.bookName); $(function(){ //是否存在购物车 var isHasCart="${sessionScope.sc == null}"; alert(isHasCart); //不存在就隐藏 if(isHasCart=="true"){ $("#cartstatus").hide(); } else{ $("#cartstatus").show(); $("#bookName").text("${sessionScope.sc.bookName}"); $("#totalBookNumber").text("${sessionScope.sc.totalBookNumber}"); $("#totalMoney").text("${sessionScope.sc.totalMoney}"); } $("a").click(function(){ $("#cartstatus").show(); var url =this.href; var args={"time":new Date()}; $.getJSON(url,args,function(data){ $("#bookName").text(data.bookName); $("#totalBookNumber").text(data.totalBookNumber); $("#totalMoney").text(data.totalMoney); }); return false; }); }) </script>
</head>
<body>
<div id="cartstatus">
您已经将 <span id ="bookName"></span> 加入到购物车,
购物车中的书有 <span id ="totalBookNumber"></span> 本,
总价格 <span id ="totalMoney"></span> 元
</div>
<br></br>
java <a href="${pageContext.request.contextPath }/addToCart?id=java&price=100">加入购物车</a>
<br></br>
Oracle <a href="${pageContext.request.contextPath }/addToCart?id=Oracle&price=200">加入购物车</a>
<br></br>
Struts2 <a href="${pageContext.request.contextPath }/addToCart?id=struts2&price=300">加入购物车</a>
<br></br>
</body>
</html>
shoppingCartItem.java
package com.sjxy.app.bean;
import java.util.HashMap;
import java.util.Map;
public class shoppingCartItem {
private int number;
private String bookName;
private int price;
/** * @return the number */
public int getNumber() {
return number;
}
/** * @param number the number to set */
public void setNumber(int number) {
this.number = number;
}
/** * @return the bookName */
public String getBookName() {
return bookName;
}
/** * @param bookName the bookName to set */
public void setBookName(String bookName) {
this.bookName = bookName;
}
/** * @return the price */
public int getPrice() {
return price;
}
/** * @param price the price to set */
public void setPrice(int price) {
this.price = price;
}
}
ShoppingCarts.java
package com.sjxy.app.bean;
import java.util.HashMap;
import java.util.Map;
public class ShoppingCarts {
private Map<String,shoppingCartItem> item=new HashMap<String,shoppingCartItem>();
private String bookName;
public void addToCart(String bookName,int price){
this.bookName=bookName;
if(item.containsKey(bookName)){
shoppingCartItem it=item.get(bookName);
it.setNumber(it.getNumber()+1);
}
else{
shoppingCartItem item1 =new shoppingCartItem();
item1.setBookName(bookName);
item1.setNumber(1);
item1.setPrice(price);
item.put(bookName,item1);
}
}
public int getTotalBookNumber(){
int total=0;
for(shoppingCartItem item2:item.values()){
total+=item2.getNumber();
}
return total;
}
public String getBookName() {
return bookName;
}
public int getTotalMoney(){
int money=0;
for(shoppingCartItem item2:item.values()){
money+=item2.getNumber() * item2.getPrice();
}
return money;
}
}
addToCart.java Servlet
package com.sjxy.app.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sjxy.app.bean.ShoppingCarts;
/** * Servlet implementation class addToCart */
@WebServlet("/addToCart")
public class addToCart extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
doPost(request,response);
}
/** * @see HttpServlet#doPost(HttpServletRequest request,HttpServletResponse response) */
protected void doPost(HttpServletRequest request,IOException {
String bookName=request.getParameter("id");
int price=Integer.parseInt(request.getParameter("price"));
//获取购物车对象
HttpSession session=request.getSession();
ShoppingCarts sc=(ShoppingCarts) session.getAttribute("sc");
if(sc==null){
sc=new ShoppingCarts();
session.setAttribute("sc",sc);
}
sc.addToCart(bookName,price);
//准备响应的json对象
//StringBuilder result=new StringBuilder();
/* result.append("{") .append("\"bookName\":\"" + bookName+"\"") .append(",") .append("\"totalBookNumber\":"+sc.getTotalBookNumber()) .append(",") .append("\"totalMoney\":"+sc.getTotalMoney()) .append("}");*/
//使用jackson将sc转化为json字符串
ObjectMapper mapper=new ObjectMapper();
String result=mapper.writeValueAsString(sc);
System.out.println(result);
response.setContentType("text/javascript");
response.getWriter().print(result);
}
}