您好,登錄后才能下訂單哦!
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 }/script/jquery.js"></script>
<script type="text/javascript">
$(function(){
var isHasCart = "${sessionScope.sc == null}";
if(isHasCart == "true"){
$("#status").hide();
}else {
$("#status").show();
//這里的sc是ShoppingCart的對象他會去調用sc.屬性對應的get方法
$("#bookName").text("${sessionScope.sc.bookName}");
$("#totalNumber").text("${sessionScope.sc.totalNumber}");
$("#totalMoney").text("${sessionScope.sc.totalMoney}");
}
$("a").click(function(){
//顯示指定的選擇器
$("#status").show();
var url = this.href;
var args = {"time":new Date()};
$.getJSON(url, args, function(data){
$("#bookName").text(data.bookName);
$("#totalNumber").text(data.totalNumber);
$("#totalMoney").text(data.totalMoney);
});
return false;
});
});
</script>
</head>
<body>
<div id="status">
您已經將 <span id="bookName"></span>
加入到購物車,購物車中的書有 <span id="totalNumber"></span> 本,
總價格 <span id="totalMoney"></span> 元。
<br><br>
</div>
Java <a href="${pageContext.request.contextPath}/addToCart?id=Java&price=150">加入購物車</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=100">加入購物車</a>
<br><br>
</body>
</html>
//SERVLET類 package com.ajax.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.ajax.beans.ShoppingCart; import com.fasterxml.jackson.databind.ObjectMapper; @WebServlet("/addToCart")//這里這樣寫注解后就不用再web.xml中配置servlet了 public class AddToCartServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.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 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":"","totalNumber":1,"totalMoney":1} //這里的\"相當于一個' 但是這里不能寫' /* StringBuilder result = new StringBuilder(); result.append("{") .append("\"bookName\":\""+bookName+"\"") .append(",") .append("\"totalNumber\":"+sc.getTotalNumber()) .append(",") .append("\"totalMoney\":"+sc.getTotalMoney()) .append("}"); response.setContentType("text/javascript"); response.getWriter().print(result.toString());*/ ObjectMapper mapper = new ObjectMapper(); response.setContentType("text/javascript"); System.out.println(mapper.writeValueAsString(sc)); //響應ShoppingCart對象的JSON字符串 response.getWriter().print(mapper.writeValueAsString(sc)); } } //ShoppingCart類 package com.ajax.beans; import java.util.HashMap; import java.util.Map; public class ShoppingCart { //存放shoppingcartItem 的鍵 書名:值 private Map<String, ShoppingCartItem> items = new HashMap<>(); private String bookName; public void addToCart(String bookName, int price){ this.bookName = bookName; if(items.containsKey(bookName)){ ShoppingCartItem item = items.get(bookName); item.setNumber(item.getNumber() + 1); item.setPrice(item.getPrice()+price); }else { ShoppingCartItem item = new ShoppingCartItem(); item.setBookName(bookName); item.setPrice(price); item.setNumber(1); items.put(bookName, item); } } public int getTotalNumber(){ int total = 0; for(ShoppingCartItem item: items.values()){ total += item.getNumber(); } return total; } public int getTotalMoney(){ int money = 0; for(ShoppingCartItem item: items.values()){ money += item.getPrice(); } return money; } public String getBookName() { return bookName; } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。