<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
ShoppingCartItem.java
public class ShoppingCartItem { private int number; private String bookName; private int price; //...}
ShoppingCart.java 购物车
public class ShoppingCart { //key:书名 value:ShoppingCartItem对象 private Mapitems = new HashMap (); private String bookName; public void addToCart(String bookName, int price) { this.bookName = bookName; if (items.containsKey(bookName)) { ShoppingCartItem shoppingCartItem = items.get(bookName); shoppingCartItem.setNumber(shoppingCartItem.getNumber() + 1); }else{ ShoppingCartItem shoppingCartItem = new ShoppingCartItem(); shoppingCartItem.setBookName(bookName); shoppingCartItem.setNumber(1); shoppingCartItem.setPrice(price); items.put(bookName, shoppingCartItem); } } public int getTotalBookNum() { 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.getNumber() * item.getPrice(); } return money; } public String getBookName() { return bookName; }}
addToCart.java servlet
String bookName = request.getParameter("id"); int price = Integer.parseInt(request.getParameter("price")); ShoppingCart shoppingCart = (ShoppingCart) request.getSession().getAttribute("shoppingCart"); if (shoppingCart == null) { shoppingCart = new ShoppingCart(); request.getSession().setAttribute("shoppingCart", shoppingCart); } shoppingCart.addToCart(bookName, price); StringBuilder result = new StringBuilder(); result.append("{") //必须用双引号 .append("\"bookName\":\"" + bookName + "\"") .append(",") .append("\"totalBookNum\":" + shoppingCart.getTotalBookNum()) .append(",") .append("\"totalMoney\":" + shoppingCart.getTotalMoney()) .append("}"); response.setContentType("text/javascript"); response.getWriter().print(result.toString());
补充:Jackson的使用
public class Customer { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCity() { return "北京"; } //忽略一个getter属性 @JsonIgnore public String getBirth() { return "1990-12-31"; } public Customer(int id, String name) { super(); this.id = id; this.name = name; } public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); Customer customer = new Customer(0, "umgsai"); String jsonString = mapper.writeValueAsString(customer); System.out.println(jsonString); //Jackson使用getter方法来定位JSON对象的属性 //{"name":"umgsai","id":0,"city":"北京"} }}
本例使用的Jar包是jackson-all-1.7.6.jar
教程中加的是下面三个包
jackson-annotation-2.2.2.jar
jackson-core-2.2.2.jar
jackson-databind-2.2.2.jar