JavaWeb_购物案例

DB位于db包

package cn.itcast.db;
import java.util.LinkedHashMap;
import java.util.Map;
import cn.itcast.domain.Book;
public class DB {
  private static Map<String,Book> map=new LinkedHashMap<String,Book>();
  static{
    map.put("1", new Book("1","javascript","老张",59,"一本好书"));
    map.put("2", new Book("2","javase","老毕",69,"一本好书"));
    map.put("3", new Book("3","javaweb","老方",79,"一本好书"));
    map.put("4", new Book("4","struts","老方",89,"一本好书"));
    map.put("5", new Book("5","hibernate","老方",49,"一本好书"));
    map.put("6", new Book("6","android","老黎",39,"一本好书"));
  }
  public static Map<String, Book> getAll(){
    return map;
  }
}
BookDao位于dao包

package cn.itcast.dao;
import java.util.Map;
import cn.itcast.db.DB;
import cn.itcast.domain.Book;
public class BookDao {
	public Map<String , Book> getAll(){
		return DB.getAll();
	}
	public Book find(String id){
		return DB.getAll().get(id);
	}
}

Book位于domain包

package cn.itcast.domain;
public class Book {
  private String id;
  private String name;
  private String author;
  private double price;
  private String description;
  public Book() {
    super();
  }
  public Book(String id, String name, String author, double price,
      String description) {
    super();
    this.id = id;
    this.name = name;
    this.author = author;
    this.price = price;
    this.description = description;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public String getAuthor() {
    return author;
  }
  public void setAuthor(String author) {
    this.author = author;
  }
  public double getPrice() {
    return price;
  }
  public void setPrice(double price) {
    this.price = price;
  }
  public String getDescription() {
    return description;
  }
  public void setDescription(String description) {
    this.description = description;
  }
}
Cart位于domain包

package cn.itcast.domain;
import java.util.LinkedHashMap;
import java.util.Map;
public class Cart {
  //购物车里面有所有购物项(CartItem),用map维护,键盘是id号,值是购物项(book和数目)
  private Map<String,CartItem> map=new LinkedHashMap<String,CartItem>();
  private double price;//购物车的总价值
  //方法添加书(分情况讨论)
  public void add(Book book){
    CartItem item=map.get(book.getId());
    if(item==null){
      item=new CartItem();
      item.setBook(book);
      item.setQuantity(1);
      map.put(book.getId(), item);
    }else{
      //否则,书已经有了,就把数量加1
      item.setQuantity(item.getQuantity()+1);
    }
  }
  public Map<String, CartItem> getMap() {
    return map;
  }
  public void setMap(Map<String, CartItem> map) {
    this.map = map;
  }
  public double getPrice() {
    //迭代map算出购物车的总价值
    double totalPrice=0;
    for (Map.Entry<String,CartItem>   entry : map.entrySet()) {
      CartItem item=entry.getValue();
      totalPrice+=item.getPrice();
    }
    this.price=totalPrice;
    return price;
  }
  public void setPrice(double price) {
    this.price = price;
  }
  
}
CartItem位于domain包

package cn.itcast.domain;
public class CartItem {
  private Book book;
  private int quantity;
  private double price;//代表单种商品的总计
  public Book getBook() {
    return book;
  }
  public void setBook(Book book) {
    this.book = book;
  }
  public int getQuantity() {
    return quantity;
  }
  public void setQuantity(int quantity) {
    this.quantity = quantity;
    this.price=this.book.getPrice()*this.quantity;
  }
  public double getPrice() {
    return price;
  }
  public void setPrice(double price) {
    this.price = price;
  }
  
}
ListBookServlet位于web.controller包

package cn.itcast.web.controller;
import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Book;
import cn.itcast.service.BusinessService;
public class ListBookServlet extends HttpServlet {
/*当在首页上点击超链接:显示所有书籍时,转到这儿
 * ListBookServlet调用BusinessService业务服务取出所有书的集合
 * 将集合存到request域里面,
 * 转发到listbook.jsp,由listbook.jsp从域里面取出所有书籍显示
 */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    BusinessService service=new BusinessService();
    Map<String, Book> map=service.getAll();
    request.setAttribute("map", map);
    request.getRequestDispatcher("/WEB-INF/jsp/listbook.jsp").forward(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
BusinessService位于service包

package cn.itcast.service;

import java.util.Map;

import cn.itcast.dao.BookDao;
import cn.itcast.domain.Book;
import cn.itcast.domain.Cart;

public class BusinessService {
//对外提供所有的业务服务
  BookDao dao=new BookDao();
  //服务1:得到所有书
  public Map<String, Book> getAll(){
    return dao.getAll();
  }
  //服务2:根据id查找某书
  public Book find(String id){
    return dao.find(id);
  }
  //服务3:根据id和购物车cart,移除购物车的map集合里对应的购物项
  public void deleteCartItem(String id, Cart cart) {
    cart.getMap().remove(id);
  }
  //服务4:将购物车cart里面的成员map清空
  public void clearCart(Cart cart) {
    cart.getMap().clear();
  }
  //服务4:设置购物车cart的成员map中的值(CartItem)的数量
  public void changeItemQuantity(String id, String quantity, Cart cart) {
    cart.getMap().get(id).setQuantity(Integer.parseInt(quantity));
  }
  
}
BuyServlet位于web.controller包

package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Book;
import cn.itcast.domain.Cart;
import cn.itcast.service.BusinessService;
public class BuyServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String id=request.getParameter("id");
    BusinessService service=new BusinessService();
    Book book=service.find(id);
    //从Session得到用户的购物车Cart,将book添加进去
    Cart cart=(Cart) request.getSession().getAttribute("cart");
    //用户第一次买,没有购物车,为其创建一个Cart,并存到session
    if (cart==null) {
      cart=new Cart();
      request.getSession().setAttribute("cart", cart);
    }
    //至此,每个用户都有一个购物车Cart
    cart.add(book);
    //完成购买后,跳转到购物车显示页面(listcart.jsp)
    //request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    //跳转到购物车,使用重定向,由于WEB-INF禁止浏览器访问,先跳ListCartServlet
    String path=request.getContextPath();///day10
    response.sendRedirect(path+"/servlet/ListCartServlet");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
deleteItemServlet位于web.controller包

package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Cart;
import cn.itcast.service.BusinessService;
public class deleteItemServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /*
     * 调用service删除购物车里指定的购物项
     */
    String id=request.getParameter("id");
    Cart cart=(Cart) request.getSession().getAttribute("cart");
    BusinessService service=new BusinessService();
    service.deleteCartItem(id,cart);
    //删除成功后,依然跳回listcart.jsp(转发-刷新会再删一次)
    //request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    //跳转到购物车,使用重定向,由于WEB-INF禁止浏览器访问,先跳ListCartServlet
    String path=request.getContextPath();///day10
    response.sendRedirect(path+"/servlet/ListCartServlet");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
ClearCartServlet位于web.controller包

package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Cart;
import cn.itcast.service.BusinessService;
public class ClearCartServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /*
     * 调用service的方法,清空购物车!
     */
    Cart cart=(Cart) request.getSession(false).getAttribute("cart");
    BusinessService service=new BusinessService();
    service.clearCart(cart);
    //清空cart里面的map后,依然跳回listcart.jsp(转发-刷新会再清空一次,无所谓!)
    //request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    //跳转到购物车,使用重定向,由于WEB-INF禁止浏览器访问,先跳ListCartServlet
    String path=request.getContextPath();///day10
    response.sendRedirect(path+"/servlet/ListCartServlet");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
ChangeQuantityServlet位于web.controller包

package cn.itcast.web.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.domain.Cart;
import cn.itcast.service.BusinessService;
public class ChangeQuantityServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    /*
     * 将购物车中cart的书修改为指定数量
     */
    String id=request.getParameter("id");
    String quantity=request.getParameter("quantity");
    String regex="[1-9]\\d*";
    boolean b=quantity.matches(regex);
    if(!b){
      request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
      return;
    }
    Cart cart=(Cart) request.getSession().getAttribute("cart");
    BusinessService service=new BusinessService();
    service.changeItemQuantity(id,quantity,cart);
    //设置购物车cart的成员map中的值(CartItem)的数量后,跳回listcart.jsp(转发-刷新会再设置一次,无所谓!)
    //request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    //跳转到购物车,使用重定向,由于WEB-INF禁止浏览器访问,先跳ListCartServlet
    String path=request.getContextPath();///day10
    response.sendRedirect(path+"/servlet/ListCartServlet");
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
ListCartServlet位于web.UI包

package cn.itcast.web.ui;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListCartServlet extends HttpServlet {
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }
}
index.jsp位于web应用根目录

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>网站首页</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
  </head>
  <a href="${pageContext.request.contextPath }/servlet/ListBookServlet">浏览书籍</a>
  <body>
  </body>
</html>
listbook.jsp位于WEB-INF/jsp文件夹内

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>书籍列表页面</title>
  </head>
  <body style="text-align: center;">
  <h2>书籍列表</h2>
    <table width="70%" border="1">
      <tr>
        <td>书名</td>
        <td>作者</td>
        <td>售价</td>
        <td>操作</td>
        <td>描述</td>
      </tr>
      <c:forEach var="entry" items="${map}">
        <tr>
          <td>${entry.value.name }</td>
          <td>${entry.value.author }</td>
          <td>${entry.value.price }</td>
          <td>${entry.value.description }</td>
          <td><a href="${pageContext.request.contextPath }/servlet/BuyServlet?id=${entry.value.id }" target="_blank">购买</a> </td>
        </tr>
      </c:forEach>
    </table>
  </body>
</html>
listcart.jsp位于WEB-INF/jsp文件夹内

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>购物车列表</title>
    <script type="text/javascript">
        /*因为是先加载,所以传id进来*/
        function deleteItem(id){
          var b=window.confirm("您确认删除吗?");
          if(b){
            window.location.href="${pageContext.request.contextPath }/servlet/deleteItemServlet?id="+id;
          }
        }
        function clearCart(){
          var b=window.confirm("您确认删除吗?");
          if(b){
            window.location.href="${pageContext.request.contextPath }/servlet/ClearCartServlet";
          }
        }
        function changeQuantity(input,id,oldNum){
          var quantity=input.value;
          /*
          //先检查是不是数字
          if(isNaN(quantity)){
            alert("请输入正整数!");
            input.value=oldNum;
            return;
          }*/
          if(quantity<0||quantity!=parseInt(quantity)){
            input.value=oldNum;
            alert("请输入正整数!");
            input.focus();
            return;
          }
          var b=window.confirm("您确定购买"+quantity+"本吗?");
          if(b){
            window.location.href="${pageContext.request.contextPath }/servlet/ChangeQuantityServlet?id="+id+"&quantity="+quantity;
          }else{
            input.value=oldNum;
          }
        }
    </script>
  </head>
<body style="text-align: center;">
  <h2>购物车列表</h2>
  <c:if test="${empty(cart.map)}">
  您尚未购买任何商品
    <a href="${pageContext.request.contextPath }/servlet/ListBookServlet">浏览书籍</a>
  </c:if>
  <c:if test="${!empty(cart.map)}">
    <table width="70%" border="1">
      <tr>
        <td>书名</td>
        <td>作者</td>
        <td>单价</td>
        <td>数量</td>
        <td>小计</td>
        <td>操作</td>
      </tr>
      <c:forEach var="entry" items="${cart.map}">
        <tr>
          <td>${entry.value.book.name }</td>
          <td>${entry.value.book.author }</td>
          <td>${entry.value.book.price }</td>
          <td><input style="width: 35px;" type="text" value="${entry.value.quantity}" onchange="changeQuantity(this,${entry.key },${entry.value.quantity})"/> </td>
          <td>${entry.value.price}</td>
          <td><a href="javascript:void(0)" onclick="deleteItem(${entry.key })">删除</a> </td>
        </tr>
      </c:forEach>
      <tr>
        <td colspan="3">总计</td>
        <td colspan="2">${cart.price }元</td>
        <td>
          <a href="javascript:void(0)" onclick="clearCart()">清空购物车</a> 
      </td>
      </tr>      
    </table>
  </c:if>
  </body>
</html>
















你可能感兴趣的:(jsp,servlet,javaweb)