cartservlet.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 92 行

JAVA
92
字号
package store;

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;


public class CartServlet extends HttpServlet {


  public void doPost(HttpServletRequest req, HttpServletResponse res)
          throws ServletException, IOException {

    doGetOrPost(req,res);

  }
  public void doGet(HttpServletRequest req, HttpServletResponse res)
          throws ServletException, IOException {

    doGetOrPost(req,res);

  }

  private void doGetOrPost(HttpServletRequest req, HttpServletResponse res)
          throws ServletException, IOException {

    //  Check to see if we are adding to the cart or
    //  if we want to dispay the cart
    String adding = req.getParameter("add");

    PrintWriter out = res.getWriter();

    //  Get the cart if it exists
    HttpSession session = req.getSession();

    Cart cart = (Cart) session.getAttribute("cart");

    if (cart == null) {
      cart = new Cart();
    }

    if (adding.equalsIgnoreCase("true")) {
      //  Add to it
      addToCart(req, cart, out);
    }

    //  Display its contents
    displayCart(cart, out);



  }

  private void addToCart(HttpServletRequest req, Cart cart, PrintWriter out) throws ItemAlreadyAddedException {
    //  Get the item to add from the request

    //  Get the products from the servletcontext
    HashMap products = (HashMap) getServletContext().getAttribute("products");
    //  Find the one represented by the ID that we passed in
    try {
      Integer id = new Integer(Integer.parseInt(req.getParameter("id")));

      Product p = (Product) products.get(id);
      //  Add it to the cart
      cart.addItem(p);
      //  add the cart to the session
      req.getSession().setAttribute("cart",cart);

      out.println("<b>Succesfully added product to cart!</b><br>");

    } catch (NumberFormatException nfe) {
      out.println("<b>Can't add product</b><br>");
    }
  }

  private void displayCart(Cart cart, PrintWriter out) {

    Iterator items = cart.getItems();
    out.println("<h1>Current Cart Contents:</h1>");
    out.println("<table>");
    while (items.hasNext()) {
      out.println("<tr>");
      Product p = (Product)items.next();
      out.println("<td>" + p.getName() + "</td>" + "<td>" + p.getPrice() +"</td>");
      out.println("<tr>");
    }
    out.println("</table>");
  }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?