product类:

package com.lab;
public class Product {
 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;
    }
    // 各属性的setter方法和getter方法
    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;
 }
}

showshoppingitem类:

package com.lab;
import java.io.Serializable;

public class ShoppingItem implements Serializable {
 private Product product;  // 商品信息
    private int quantity;      // 商品数量
 
    public ShoppingItem(Product product, int quantity) {
        this.product = product;
        this.quantity = quantity;
    }
    // 属性的getter方法和setter方法
    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;
 }
}

ShoppingCartServlet

package com.lab;
import com.lab.Product;
import com.lab.ShoppingItem;
import java.io.*;
import java.util.ArrayList;
//import java.awt.List;
import java.util.List;
import java.awt.Component;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.Serializable;
import javax.servlet.annotation.WebServlet;

@WebServlet(name = "ShoppingCartServlet", urlPatterns = {
        "/products", "/viewProductDetails",
        "/addToCart", "/viewCart", "/deleteItem"  })

public class ShoppingCartServlet extends HttpServlet {
 
 
    // products是存放所有商品的List对象
private List  <Product>  products = new ArrayList <Product>();

@Override
    public void init() throws ServletException {
        products.add(new Product(1, "单反相机",
                "尼康性价比最高的单反相机",4159.95F));
        products.add(new Product(2, "三星手机",
                "三星公司的最新iPhone5产品", 1199.95F));
        products.add(new Product(3, "笔记本电脑",
                "联想公司的新一代产品",5129.95F));
        products.add(new Product(4, "平板电脑",
                "苹果公司的新产品",1239.95F));
    }

@Override
    public void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {
        String uri = request.getRequestURI();
        // 根据请求URI决定调用哪个方法
if (uri.endsWith("/products")) {
            showProductList(response);
        } else if (uri.endsWith("/viewProductDetails")) {
            showProductDetails(request, response);
        } else if (uri.endsWith("viewCart")) {
            showCart(request, response);
        } else if (uri.endsWith("deleteItem")) {
            deleteItem(request, response);
        }
    }
   
   
    // 该方法用于显示所有商品信息
private void showProductList(HttpServletResponse response)
            throws IOException {
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        out.println("<html><head><title>商品列表</title>" +
          "</head><body><p>商品列表</p>");
        out.println("<ul>");
        for (Product product : products) {
            out.println("<li>" + product.getName() + "("
                    + product.getPrice()
                    + ") (" + "<a href='viewProductDetails?id="
                    + product.getId() + "'>详细信息</a>)");
        }
        out.println("</ul>");
        out.println("<a href='viewCart'>查看购物车</a>");
        out.println("</body></html>");
     }
    
    
private void showProductDetails(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
      response.setContentType("text/html;charset=gb2312");
      PrintWriter out = response.getWriter();
      int productId = 0;
      try {
          productId = Integer.parseInt(
                  request.getParameter("id"));
      } catch (NumberFormatException e){
      }
      // 根据商品号返回商品对象
      Product product = getProduct(productId);

if (product != null) {
          out.println("<html><head>"
                  + "<title>商品详细信息</title></head>"
                  + "<body><p>商品详细信息</p>"
                  + "<form method='post' action='addToCart'>");
          // 这里使用隐藏表单域存储商品号信息
out.println("<input type='hidden' name='id' "
            + "value='" + productId + "'/>");
          out.println("<table>");
          out.println("<tr><td>商品名:</td><td>"
                  + product.getName() + "</td></tr>");
         
          out.println("<tr><td>说明:</td><td>"
                  + product.getDescription() + "</td></tr>");
          out.println("<tr><td>价格:</td><td>"
                  + product.getPrice() + "</td></tr>");
         
          out.println("<tr>" + "<tr>"
                  + "<td><input name='quantity'/></td>"
                  + "<td><input type='submit' value='购买'/>"
                  + "</td>"
                  + "</tr>");
          out.println("<tr><td colspan='2'>"
                  + "<a href='products'>商品列表</a>"
                  + "</td></tr>");
          out.println("</table>");
          out.println("</form></body>");
      } else {
          out.println("No product found");
      }
  }
 
 
// 根据商品号返回商品对象方法
private Product getProduct(int productId) {
     for (Product product : products) {
         if (product.getId() == productId) {
              return product;
         }
     }
    return null;
}

public void doPost(HttpServletRequest request,
                       HttpServletResponse response)
throws ServletException, IOException {
     // 将购买的商品添加到购物车中
     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);
          HttpSession session = request.getSession();
          // 在会话对象中查找购物车对象
List<ShoppingItem> cart = (List<ShoppingItem>) session
                    .getAttribute("cart");
          if (cart == null) {
               // 如果在会话对象上找不到购物车对象,则创建一个
               cart = new ArrayList<ShoppingItem>();
               // 将购物车对象存储到会话对象上
session.setAttribute("cart", cart);
            }
            // 将商品添加到购物车对象中
cart.add(shoppingItem);
      }
      showProductList(response);
 }

public void deleteItem(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int productId = 0,i=0;
try {
productId = Integer.parseInt(
request.getParameter("id"));
} catch (NumberFormatException e) { }
HttpSession session = request.getSession();
List<ShoppingItem> cart = (List<ShoppingItem>) session.getAttribute("cart");
for (i=0;i<cart.size();i++){
ShoppingItem p=cart.get(i);
if (p.getProduct().getId()==productId)
{
cart.remove(i);
break;
}
}
response.sendRedirect("http://localhost:8080/helloapp/viewCart");
}

private void showCart(HttpServletRequest request,
            HttpServletResponse response) throws IOException {
     response.setContentType("text/html;charset=gb2312");
     PrintWriter out = response.getWriter();
     out.println("<html><head><title>购物车</title></head>");
     out.println("<body><a href='products'>" +
          "商品列表</a>");
     HttpSession session = request.getSession();
     List<ShoppingItem> cart = (List<ShoppingItem>) session
                .getAttribute("cart");
     if (cart != null) {
         out.println("<table>");
         out.println("<tr><td style='width:50px'>数量"
           + "</td>"
              + "<td style='width:80px'>商品</td>"
              + "<td style='width:80px'>价格</td>"
              + "<td style='width:80px'>小计</td>"
              + "<td style='width:80px'>是否删除</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();
                 out.println("<tr>");
                 out.println("<td>" + quantity + "</td>");
                 out.println("<td>" + product.getName()
                         + "</td>");
                 out.println("<td>" + price  + "</td>");
                 // 计算小计并实现四舍五入
double subtotal = ((int)(price * quantity*100+0.5))/100.00;
                out.println("<td>" + subtotal + "</td>");
                 out.println("<td><a href=deleteItem?id=" +
                   product.getId()+">"+"删除</a>" + "</td>");
                 total += subtotal;
                 out.println("</tr>");
              }
          }
          out.println("<tr><td colspan='4' "
                  + "style='text-align:right'>"
                  + "总计:" + total  + "</td></tr>");
          out.println("</table>");
     }
      out.println("</table></body></html>");
}
}

javaweb实验五的更多相关文章

  1. 20145215&20145307《信息安全系统设计基础》实验五 网络通信

    小组成员:20145215卢肖明.20145307陈俊达 实验报告链接:信息安全系统设计基础--实验五实验报告

  2. 20145216 20145330 《信息安全系统设计基础》 实验五 简单嵌入式WEB 服务器实验

    20145216 20145330 <信息安全系统设计基础> 实验五 简单嵌入式WEB 服务器实验 实验报告封面 实验步骤 1.阅读理解源码 进入/arm2410cl/exp/basic/ ...

  3. 20145208《信息安全系统设计基础》实验五 简单嵌入式WEB 服务器实验

    20145208<信息安全系统设计基础>实验五 简单嵌入式WEB 服务器实验 20145208<信息安全系统设计基础>实验五 简单嵌入式WEB 服务器实验

  4. 20145315&20145307《信息安全系统设计基础》实验五

    20145315&20145307<信息安全系统设计基础>实验五 北京电子科技学院(BESTI) 实 验 报 告 课程:信息安全系统设计基础 班级:1453 1452 姓名:陈俊达 ...

  5. 实验五(简单嵌入式WEB服务器实验)问题总结

    实验五问题总结 问题链接:<信息安全系统设计基础>实验五实验报告 虽然将07_httpd文件中全部拷贝进了bc中,文件夹中拥有Makefile文件,但是还是无法通过make得到该文件夹中c ...

  6. 20145210 20145226 《信息安全系统设计基础》实验五 简单嵌入式WEB服务器实验

    20145210 20145226 <信息安全系统设计基础>实验五 简单嵌入式WEB服务器实验 结对伙伴:20145226 夏艺华 实验报告封面 实验目的与要求 · 掌握在ARM开发板实现 ...

  7. Java实验五

    20145113 Java实验五 网络编程及安全 实验内容 对于客户端与服务器端:修改原代码,使其可以实现连续的传消息,并且传送文件. 对于加解密部分: 对于原先的加密只加密"hello w ...

  8. 20145316&20145229实验五:网络通信

    20145316&20145229实验五:网络通信 结对伙伴:20145316 博客链接:http://www.cnblogs.com/xxy745214935/p/6130897.html

  9. 20145301&20145321&20145335实验五

    20145301&20145321&20145335实验五 这次实验我的组员为:20145301赵嘉鑫.20145321曾子誉.20145335郝昊 实验内容详见:实验五

随机推荐

  1. System.Web.Caching.Cache类 缓存

    1.文件缓存依赖 public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender ...

  2. 苹果推送(APNs)ios push小结

    把app删除后就推送不成功了,可以看出deviceToken应该是设备+app来一起识别的,重新安装后仍然为同一个 简介 推送服务APNs(Apple Push Notification servic ...

  3. 读懂Android项目结构目录

    我们看到下图:当我们创建了第一Android项目的时候有没有被吓到.怎么这么多目录,好头晕啊!没事, 那我们今天就了解一下这些目录是做什么的: src: src 目录是放置我们所有 Java 代码的地 ...

  4. css 让内容满屏居中不变形

    .selector { position: fixed; width: 100%; height: 100%; background-image: url(path); background-repe ...

  5. 《DSP using MATLAB》示例Example4.10

    上代码: b = [1, 0.4*sqrt(2)]; a = [1, -0.8*sqrt(2), 0.64]; % compute the polynomials coefficients given ...

  6. maven 各种用途

    1.maven 管理项目编译 作为项目编译代码管理工具,可以方便的进行编译集成. 2. maven 扩展单元测试 扩展对接junit可以方便进行单元测试 3.maven profiles各种devel ...

  7. Appium Java Windows环境搭建篇

    1. 安卓SDK及配置环境变量 1.1.先下载sdk安装包:installer_r24.4.1-windows.exe 下载地址:链接: http://pan.baidu.com/s/1dEyPSa9 ...

  8. 矩阵快速幂 UVA 10870 Recurrences

    题目传送门 题意:f(n) = a1f(n − 1) + a2f(n − 2) + a3f(n − 3) + . . . + adf(n − d), for n > d,求f (n) % m.训 ...

  9. POJ3680 Intervals(最小费用最大流)

    选择若干条线段使权值最大,并且点覆盖次数不超过k. 建图如下:vs到0建立容量为k费用为0的边:坐标终点到vt连接一条容量为k费用为0的边:对于每两个相邻坐标连接一条容量为INF费用为0的边:对于线段 ...

  10. 【Oracle】Oracle时间日期格式

    to_date("要转换的字符串","转换的格式")   两个参数的格式必须匹配,否则会报错. 即按照第二个参数的格式解释第一个参数. to_char(日期,& ...