Ajax 简单购物车工程

前端之家收集整理的这篇文章主要介绍了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 }/scripts/jquery.js">
</script>

<script type="text/javascript">
	$(function(){
		var isHasCart = "${sessionScope.sc==null}";
		if(isHasCart){
			$("#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>元<br>
	</div>
	Java   <a href="${pageContext.request.contextPath }/addToCart?id=Java&price=100">加入购物车</a><br>
	Oracle <a href="${pageContext.request.contextPath }/addToCart?id=Oracle&price=200">加入购物车</a><br>
	Struts2<a href="${pageContext.request.contextPath }/addToCart?id=Struts2&price=100">加入购物车</a><br>
	
</body>
</html>
AddToCart.java
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.trekiz.beans.ShoppingCart;

/**
 * Servlet implementation class AddToCart
 */
@WebServlet("/addToCart")
public class AddToCart extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddToCart() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request,HttpServletResponse response)
	 */
	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();
		ShoppingCart sc = (ShoppingCart) session.getAttribute("sc");
		if(sc==null){
			sc = new ShoppingCart();
			session.setAttribute("sc",sc);
		}
		sc.addToCart(bookName,price);
		//准备响应的json对象
		StringBuilder result = new StringBuilder();
		//若从服务端返回json字符串,则属性名必须使用双引号
		result.append("{")
		      .append("\"bookName\":\""+bookName+"\"")
		      .append(",")
		      .append("\"totalBookNumber\":"+sc.getTotalBookNumber())
		      .append(",")
		      .append("\"totalMoney\":"+sc.getTotalMoney())
			  .append("}");
		response.setContentType("text/javascript");
		response.getWriter().println(result.toString());
		
	}

}

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

public class ShoppingCart {
	private String bookName;
	private Map<String,ShoppingCartItem> items = new HashMap<String,ShoppingCartItem>();
	
	public void addToCart(String bookName,int price){
		this.bookName = bookName;
		if(items.containsKey(bookName)){
			ShoppingCartItem item = items.get(bookName);
			item.setNumber(item.getNumber()+1);
		}else{
			ShoppingCartItem item = new ShoppingCartItem();
			item.setBookName(bookName);
			item.setPrice(price);
			item.setNumber(1);
			items.put(bookName,item);
		}
	}
	
	public int getTotalBookNumber(){
		int total=0;
		for(ShoppingCartItem item : items.values()){
			total = total + item.getNumber();
		}
		return total;
	}
	
	public int getTotalMoney(){
		int money = 0;
		for(ShoppingCartItem item : items.values()){
			money = money + item.getPrice()*item.getNumber();
		}
		return money;
	}
	
	public String getBookName(){
		return this.bookName;
	}
	

}
ShoppingCartItem.java
public class ShoppingCartItem {
	
	private int number;
	
	private String bookName;
	
	private int price;

	public int getNumber() {
		return number;
	}

	public void setNumber(int number) {
		this.number = number;
	}

	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;
	}
	
	

}

拼接json字符串时,在导入jackson jar后,可以使用如下两行代码,更简便

ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(sc);

效果图:

原文链接:https://www.f2er.com/ajax/162570.html

猜你在找的Ajax相关文章