示例代码:
package com.cdc.test;
public class Product {
/** 产品id **/
private int id;
/** 产品名字 **/
private String name;
/*** 产品描述 **/
private String description;
/** 产品价钱 **/
private float price;
public Product(int id, String name, String description, float price) {
this.id = id;
this.name = name;
this.description = description;
this.price = price;
}
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 getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
package com.cdc.test;
public class ShoppingItem {
private Product product;
/***产品数量**/
private int quantity;
public ShoppingItem(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
}
package com.cdc.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
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;
@WebServlet(name = "ShoppingCartServlet", urlPatterns = { "/products",
"/viewProductDetails", "/addToCart", "/viewCart" })
public class ShoppingCartServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private static final String CART_ATTRIBUTE = "cart";
private List<Product> products = new ArrayList<Product>();
private NumberFormat currencyFormat = NumberFormat
.getCurrencyInstance(Locale.CHINA);
@Override
public void init() throws ServletException {
products.add(new Product(1, "电视机", "高清电视机", 159.95F));
products.add(new Product(2, "电脑-台式机", "联想台式机", 99.95F));
products.add(new Product(3, "笔记本电脑--联想", "联想笔记本", 129.95F));
products.add(new Product(4, "华为--硬盘", "华为高端存储", 39.95F));
}
/*** Servlet默认会调用get方法 **/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/products")) {
sendProductList(response);
} else if (uri.endsWith("/viewProductDetails")) {
sendProductDetails(request, response);
} else if (uri.endsWith("viewCart")) {
showCart(request, response);
}
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// add to cart
/** 产品的id **/
int productId = 0;
/** 产品的数量 **/
int quantity = 0;
try {
productId = Integer.parseInt(request.getParameter("id"));
quantity = Integer.parseInt(request.getParameter("quantity"));
} catch (NumberFormatException e) {
}
Product product = getProduct(productId);
if (product != null && quantity >= 0) {
ShoppingItem shoppingItem = new ShoppingItem(product, quantity);
/***获取session,并且查看里面是否有包含有一个CART_ATTRIBUTE的属性,如果有就把它添加到ShoppingItem里面,如果没有就创建一个.***/
HttpSession session = request.getSession();
@SuppressWarnings("unchecked")
List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
if (cart == null) {
cart = new ArrayList<ShoppingItem>();
/***将包含有产品数量和产品信息的集合添加到session---CART_ATTRIBUTE里面**/
session.setAttribute(CART_ATTRIBUTE, cart);
}
cart.add(shoppingItem);
}
sendProductList(response);
}
private void sendProductList(HttpServletResponse response)
throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>产品</title>"
+ "</head><body><h2>产品</h2>");
writer.println("<ul>");
for (Product product : products) {
writer.println("<li>" + product.getName() + "("
+ currencyFormat.format(product.getPrice()) + ") ("
+ "<a href='viewProductDetails?id=" + product.getId()
+ "'>详情</a>)");
}
writer.println("</ul>");
writer.println("<a href='viewCart'>查看购物车</a>");
writer.println("</body></html>");
}
private Product getProduct(int productId) {
for (Product product : products) {
if (product.getId() == productId) {
return product;
}
}
return null;
}
private void sendProductDetails(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
int productId = 0;
try {
productId = Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Product product = getProduct(productId);
if (product != null) {
writer.println("<html><head>"
+ "<title>产品详情</title></head>"
+ "<body><h2>产品详情</h2>"
+ "<form method='post' action='addToCart'>");
writer.println("<input type='hidden' name='id' " + "value='"
+ productId + "'/>");
writer.println("<table>");
writer.println("<tr><td>名称:</td><td>" + product.getName()
+ "</td></tr>");
writer.println("<tr><td>描述:</td><td>"
+ product.getDescription() + "</td></tr>");
writer.println("<tr>" + "<tr>"
+ "<td><input name='quantity'/></td>"
+ "<td><input type='submit' value='购买'/>" + "</td>"
+ "</tr>");
writer.println("<tr><td colspan='2'>"
+ "<a href='products'>产品列表</a>" + "</td></tr>");
writer.println("</table>");
writer.println("</form></body>");
} else {
writer.println("没有此产品");
}
}
private void showCart(HttpServletRequest request,
HttpServletResponse response) throws IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.println("<html><head><title>购物车</title>" + "</head>");
writer.println("<body><a href='products'>" + "产品列表</a>");
/***获取在doPost()里面设置到session里面的值**/
HttpSession session = request.getSession();
@SuppressWarnings("unchecked")
List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute(CART_ATTRIBUTE);
if (cart != null) {
writer.println("<table>");
writer.println("<tr><td style='width:150px'>数量" + "</td>"
+ "<td style='width:150px'>产品</td>"
+ "<td style='width:150px'>单价</td>"
+ "<td>总额</td></tr>");
double total = 0.0;
for (ShoppingItem shoppingItem : cart) {
Product product = shoppingItem.getProduct();
int quantity = shoppingItem.getQuantity();
if (quantity != 0) {
float price = product.getPrice();
writer.println("<tr>");
writer.println("<td>" + quantity + "</td>");
writer.println("<td>" + product.getName() + "</td>");
writer.println("<td>" + currencyFormat.format(price)
+ "</td>");
double subtotal = price * quantity;
writer.println("<td>" + currencyFormat.format(subtotal)
+ "</td>");
total += subtotal;
writer.println("</tr>");
}
}
writer.println("<tr><td colspan='4' " + "style='text-align:right'>"
+ "合计:" + currencyFormat.format(total) + "</td></tr>");
writer.println("</table>");
}
writer.println("</table></body></html>");
}
}