1. 程式人生 > >Ajax加入購物車

Ajax加入購物車

 匯入jackSonjar包 

jackson-annotations-2.2.3

jackson-core-2.2.3

jackson-databind-2.2.3

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 }/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
   $(function(){
	      var isHascart="${sesssionScope.sc==null}";
	      //沒有 購物車的時候隱藏 
	     if(isHascart=="true"){
	    	 $("#cartstatus").hide();
	     }else{
	    	 $("#cartstatus").show();
	    	 $("#bookname").text("${sesssionScope.bookname}");
			 $("#Toalbooknumber").text("${sesssionScope.Toalbooknumber}");
			 $("#totalmoney").text("${sesssionScope.totalmoney}");
	     }
	   $("a").click(function(){
		   $("#cartstatus").show();
		   var url=this.href;
		   var args={"time":new Date};
		   $.getJSON(url,args,function(data){
			   $("#bookname").text(data.bookname);
			   $("#Toalbooknumber").text(data.toalbooknumber);
			   $("#totalmoney").text(data.totalmoney);
		   })
		   return false;
	   })
   })
</script>
<!--  1.獲取當前頁面的所有a節點  並未每一個a節點都新增onclick響應函式 取消預設行為
	  2. 準備傳送ajax請求   : URL(a節點的href屬性值 ;) args(時間戳)
	  3. 簡析響應  響應為一個Json物件  :bookname toalbooknumber: totalmoney  
	  4.把對應的屬性新增到 對應的位置
	  -->
</head>
<body>
<div id="cartstatus"><!--第一次不出現  思路判斷購物車是否存在 --> 
			<!--定位   -->
   您已將&nbsp;<span id="bookname"></span>&nbsp;加入到購物車中,
   購物車中共有&nbsp;<span id="Toalbooknumber"></span>&nbsp;本書  ,
   總價格&nbsp;<span id="totalmoney"></span>&nbsp;元</div>
   <br><br>
   Java &nbsp;&nbsp;<a href="${pageContext.request.contextPath }/addtocart?id=java&price=100">加入到購物車</a>
   <br><br>
   Oracle&nbsp;&nbsp;<a href="${pageContext.request.contextPath }/addtocart?id=Oracle&price=200">加入到購物車</a>
   <br><br>
   Struts2&nbsp;&nbsp;<a href="${pageContext.request.contextPath }/addtocart?id=Struts2&price=1000">加入到購物車</a>
   <br><br>
   <br><br>
</body>
</html>

 

package com.greatest.shopping.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.greatest.addshopping.shoppingcart;

/**
 * Servlet implementation class addtocartservlet
 */
@WebServlet("/addtocart")
public class addtocartservlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	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,price
		String bookname=request.getParameter("id");
		int  price=Integer.parseInt(request.getParameter("price"));
		 //2.獲取購物車物件
		  HttpSession  sc=request.getSession();
		  shoppingcart s=(shoppingcart) sc.getAttribute("sc");
		   if(s==null){
			   s=new shoppingcart();
			   sc.setAttribute("sc", s);
		   }
		  //3.把點選 的選項加入到購物車中
		  s.addtocart(bookname, price);
		  //4.準備響應的json物件{"bookname":"",totalbooknumber:""}
		   //4.準備響應的json物件{"bookname":"",totalbooknumber:""}
//		  StringBuilder  result=new StringBuilder();
//		  result.append("{")
//		  		.append("\"bookname\":\""+bookname+"\"")
//		  		.append(",")
//		  		.append("\"toalbooknumber\":"+s.getToalbooknumber())
//		  		.append(",")
//		  		.append("\"totalmoney\":"+s.getTotalmoney())
//		  		.append("}");
		  ObjectMapper m=new ObjectMapper();
		  String result=m.writeValueAsString(s);
		  System.out.println(result);
		  //5.響應JSON物件
		  response.setContentType("text/javascript");
		  response.getWriter().print(result.toString());
	}

}

 

package com.greatest.addshopping;

import java.util.HashMap;
import java.util.Map;

public class shoppingcart {
   private   int toalbooknumber;
   private  String bookname;
   public String getBookname() {
	return bookname;
}
   //存放shoppingcatrItem的物件  鍵 書名  值  物件
   private    Map<String ,shoppingcatrItem> items=new HashMap<String ,shoppingcatrItem>();
   public void  addtocart(String bookname,int price){
	   this.bookname=bookname;
	   if(items.containsKey(bookname)){
		   //包含加一
		   shoppingcatrItem  item=items.get(bookname);
		   item.setNumber(item.getNumber()+1);
	   }else{
		   //建立一個新的
		   shoppingcatrItem  item=new shoppingcatrItem();
		   item.setBookname(bookname);
		   item.setPrice(price);
		   item.setNumber(1);
		   items.put(bookname, item);
	   }
   }
   //總數量
   public  int getToalbooknumber(){
	   int total=0;
	   for(shoppingcatrItem s:items.values()){
		   total+=s.getNumber();
	   }
	   return total;
   }
   //總價格
   public  int getTotalmoney(){
	   int money=0;
	   for(shoppingcatrItem m:items.values()){
		   money+=m.getNumber()*m.getPrice();
	   }
	   return money;
   }
}

 

package com.greatest.addshopping;

public class shoppingcatrItem {
        private int number;
        private String bookname;
         private int price;
		/* (non-Javadoc)
		 * @see java.lang.Object#toString()
		 */
		@Override
		public String toString() {
			return "shoppingcatrItem [number=" + number + ", bookname=" + bookname + ", price=" + 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;
		}
}