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. Vue#计算属性

    在模板中表达式非常便利,但是它们实际上只用于简单的操作.模板是为了描述视图的结构.在模板中放入太多的逻辑会让模板过重且难以维护.这就是为什么 Vue.js 将绑定表达式限制为一个表达式.如果需要多于一 ...

  2. loj 1377 (bfs)

    题目链接:http://lightoj.com/volume_showproblem.php?problem=1377 思路:这道题只要处理好遇到"*"这种情况就可以搞定了.我们可 ...

  3. Linux学习笔记(2)Linux学习注意事项

    1 学习Linux的注意事项 ① Linux严格区分大小写 ② Linux中所有内容均以文件形式保存,包括硬件,如硬件文件是/deb/sd[a-p] ③ Linux不靠扩展名区分文件类型,但有的文件是 ...

  4. loadrunner生成随机身份证和银行卡号

    生成银行卡号码: Action() { char card[19] = {'6','2','2','7','0','0','0','0','0','0','0','0','0','0','0','0' ...

  5. 廖雪峰js教程笔记4 sort排序的一些坑

    排序算法 排序也是在程序中经常用到的算法.无论使用冒泡排序还是快速排序,排序的核心是比较两个元素的大小.如果是数字,我们可以直接比较,但如果是字符串或者两个对象呢?直接比较数学上的大小是没有意义的,因 ...

  6. TCP粘包/拆包问题

    无论是服务端还是客户端,当我们读取或者发送消息的时候,都需要考虑TCP底层的粘包/拆包机制. TCP粘包/拆包 TCP是个"流"协议,所谓流,就是没有界限的一串数据.大家可以想想河 ...

  7. 浩瀚技术 安卓版移动开单手持微POS PDA无线移动开单软件 -安卓版移动手持开单设备

    PDA数据采集器,是深圳浩瀚技术有限公司最新研发的一款安卓版移动手持开单设备,它通过WIFI和GPRS连接并访问电脑,从进销存软件中读取数据,实现移动开单,打破电脑开单模式. 它自带扫描器,可直接扫描 ...

  8. c#中ref和out 关键字

    问题:为什么c#中要有ref和out?(而java中没有)需求假设:现需要通过一个叫Swap的方法交换a,b两个变量的值.交换前a=1,b=2,断言:交换后a=2,b=1. 现编码如下: class ...

  9. 线段树(多棵) HDOJ 4288 Coder

    题目传送门 题意:集合,add x, del x, 求和 分析:首先,暴力可以过这题.用上线段树能大大降低时间的消耗,具体就是类似开了5棵线段树,每个节点都有5个空间,表示该区间的id%5后的和,区间 ...

  10. 二叉搜索树 POJ 2418 Hardwood Species

    题目传送门 题意:输入一大堆字符串,问字典序输出每个字符串占的百分比 分析:二叉搜索树插入,然后中序遍历就是字典序,这里root 被new出来后要指向NULL,RE好几次.这题暴力sort也是可以过的 ...