Ajax+Servlet 实现购物车功能

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>

<!-- 
1. 获取当前页面所有的 a 节点,并为每一个 a 节点添加 onclick 响应函数,同时取消默认行为
2. 准备发送 Ajax 请求:url(a 节点的 href 属性值);args(时间戳)
3. 响应为一个 json 对象,包括:bookName,totalBookNumber,totalMoney
4. 把对应的属性添加到对应的位置
 -->
<script type="text/javascript" src = "${pageContext.request.contextPath}/scipts/jquery-2.1.0.js"></script>
<script type="text/javascript">
    $(function(){
        $("a").click(function(){
            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>

    您已经将&nbsp; <span id = "bookName"></span>&nbsp; 加入到购物车中。<br/>
    购物车中的书有 &nbsp; <span id = "totalBookNumber"></span>&nbsp;&nbsp;本 <br/>
    总价格&nbsp;<span id ="totalMoney"></span>&nbsp;&nbsp;钱
    <br/><br/><br/><br/>

    Java&nbsp;<a href = "${pageContext.request.contextPath}/addToCart?id=Java&price=100">加入购物车</a>
    <br/><br/>

    Oracle&nbsp;<a href = "${pageContext.request.contextPath}/addToCart?id=Oracle&price=200">加入购物车</a>
    <br/><br/>

    Struts2&nbsp;<a href = "${pageContext.request.contextPath}/addToCart?id=Struts2&price=100">加入购物车</a>
    <br/><br/>  
</body>
</html>


ShoppingCart购物车实体类

public class ShoppingCart {

    //存放 ShoppingCartItem 的 Map : 键-> 书名, 值 -> ShoppingCartItem 对象
    private Map<String,ShoppingCartItem> items = new HashMap<String,ShoppingCartItem>();

    public void addToCart(String bookName,int price){
        if(items.containsKey(bookName)) {
            ShoppingCartItem item = items.get(bookName);
            item.setNum(item.getNum()+1);
        }else {
            ShoppingCartItem item = new ShoppingCartItem();
            item.setBookName(bookName);
            item.setPrice(price);
            item.setNum(1);

            items.put(bookName, item);
        }
    }

    public int getTotalBookNumber() {
        int total = 0;

        for(ShoppingCartItem item: items.values())
            total += item.getNum();
        return total;
    }

    public int getTotalMoney() {
        int money = 0;

        for(ShoppingCartItem item: items.values())
            money += item.getNum() * item.getPrice();
        return money;
    }
}


ShoppingCartItem购物车物品类

public class ShoppingCartItem {

    private int num;

    private String bookName;

    private int price;

    public int getNum() {
        return num;
    }

    public void setNum(int num) {
        this.num = num;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }



}


服务器端Servlet代码

@WebServlet("/addToCart")
public class AddToCartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public AddToCartServlet() {
        super();
     }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取请求参数:id,prince
        String bookName = request.getParameter("id");
        int price =Integer.parseInt(request.getParameter("price"));
        //2. 获取购物车对象
        HttpSession session = request.getSession();
        ShoppingCart sc = (ShoppingCart) session.getAttribute("sc");

        if(sc == null) {
            sc = new ShoppingCart();
            session.setAttribute("sc", sc);
        }

        //3. 把点击的选项加入到购物车
        sc.addToCart(bookName, price);

        //4. 准备响应的 JSON 对象:{"bookName":"","totalBookNumber":1,"totalMoney":1}
        // 若从服务端返回 json 字符串,属性名必须是双引号
/*      StringBuilder result = new StringBuilder();
        result.append("{")
              .append("\"bookName\":\""+bookName+"\"")
              .append(",")
              .append("\"totalBookNumber\":"+sc.getTotalBookNumber())
              .append(",")
              .append("\"totalMoney\":"+sc.getTotalMoney())
              .append("}");*/
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(sc);

        //5. 响应 JSON 对象
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/javascript");
        /*response.getWriter().print(result.toString());*/
        response.getWriter().print(jsonStr);
    }

}

猜你喜欢

转载自blog.csdn.net/baidu_37181928/article/details/79330133