实例讲解JSP Model2体系结构(中)

2019-05-27 21:26:50丽君


        buylist.addElement(aCD);

      }

     }

     session.putValue("shopping.shoppingcart", buylist);

     String url="/jsp/shopping/EShop.jsp";

     ServletContext sc = getServletContext();

     RequestDispatcher rd = sc.getRequestDispatcher(url);

     rd.forward(req, res);

    } else if (action.equals("CHECKOUT")) {

     float total =0;

     for (int i=0; i< buylist.size();i++) {

      CD anOrder = (CD) buylist.elementAt(i);

      float price= anOrder.getPrice();

      int qty = anOrder.getQuantity();

      total += (price * qty);

     }

     total += 0.005;

     String amount = new Float(total).toString();

     int n = amount.indexOf('.');

     amount = amount.substring(0,n+3);

     req.setAttribute("amount",amount);

     String url="/jsp/shopping/Checkout.jsp";

     ServletContext sc = getServletContext();

     RequestDispatcher rd = sc.getRequestDispatcher(url);

     rd.forward(req,res);

    }

   }

   private CD getCD(HttpServletRequest req) {

    //想象一下如果这些都在一个脚本片段中会有多么难看

    String myCd = req.getParameter("CD");

    String qty = req.getParameter("qty");

    StringTokenizer t = new StringTokenizer(myCd,"|");

    String album= t.nextToken();

    String artist = t.nextToken();

    String country = t.nextToken();

    String price = t.nextToken();

    price = price.replace('$',' ').trim();

    CD cd = new CD();

    cd.setAlbum(album);

    cd.setArtist(artist);

    cd.setCountry(country);

    cd.setPrice((new Float(price)).floatValue());

    cd.setQuantity((new Integer(qty)).intValue());

    return cd;

   }

  }