前端之家收集整理的这篇文章主要介绍了
Ajax_典型应用_购物车添加商品,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<%@ 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}/js/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
var isHasCart="${sessionScope.sc==null}";
if(isHasCart=="true"){
$("#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>元.
<hr>
</div>
<br/><br/>
Java<a href="${pageContext.request.contextPath}/addToCart?id=java&price=11">加入购物车</a>
<br/><br/>
JavaWEB<a href="${pageContext.request.contextPath}/addToCart?id=javaweb&price=22">加入购物车</a>
<br/><br/>
JavaScript<a href="${pageContext.request.contextPath}/addToCart?id=javascript&price=33">加入购物车</a>
<br/><br/>
</body>
</html>
package org.java.beans;
public class ShoppingCarItem {
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;
}
}
package org.java.beans;
import java.util.HashMap;
import java.util.Map;
public class ShoppingCart {
private Map<String,ShoppingCarItem> items=new HashMap<String,ShoppingCarItem>();
private String bookName;
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void addToCart(String bookName,int price){
this.bookName=bookName;
if(items.containsKey(bookName)){
ShoppingCarItem item=items.get(bookName);
item.setNumber(item.getNumber()+1);
}else{
ShoppingCarItem item=new ShoppingCarItem();
item.setBookName(bookName);
item.setPrice(price);
item.setNumber(1);
items.put(bookName,item);
}
}
public int getTotalBookNumber(){
int total=0;
for(ShoppingCarItem item:items.values()){
total+=item.getNumber();
}
return total;
}
public int getTotalMoney(){
int money=0;
for(ShoppingCarItem item:items.values()){
money+=item.getNumber()*item.getPrice();
}
return money;
}
}
package org.java.test;
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 org.java.beans.ShoppingCart;
/**
* Servlet implementation class AddToCartServlet
*/
@WebServlet("/addToCart")
public class AddToCartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddToCartServlet() {
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 {
//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":"java","totalBookNumber":1,"totalMoney":1}
//若从服务端返回json字符串,属性名必须用双引号
StringBuilder result=new StringBuilder();
// JackSon 根据getter()来定位Java对象的属性
//org.codehaus.jackson.map.ObjectMapper writeValueAsString():Java对象-->json字符串
//jackson-annotations jackson-core jackson-databind jar包
//可以在类的getter方法上添加注解:org.codehaus.jackson.annotate.JsonIgnore。在转为json字符串时可以忽略该属性
result.append("{")
.append("\"bookName\":\""+bookName+"\"").append(",")
.append("\"totalBookNumber\":"+sc.getTotalBookNumber()).append(",")
.append("\"totalMoney\":"+sc.getTotalMoney()).append("}");
//5.响应json对象
response.setContentType("text/javascript");
response.getWriter().print(result.toString());
}
}
// JackSon 根据getter()来定位Java对象的属性
//org.codehaus.jackson.map.ObjectMapper writeValueAsString():Java对象-->json字符串
//jackson-annotations jackson-core jackson-databind jar包
//可以在类的getter方法上添加注解:org.codehaus.jackson.annotate.JsonIgnore。在转为json字符串时可以忽略该属性
原文链接:https://www.f2er.com/ajax/161518.html