您好,登录后才能下订单哦!
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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。