javaee学习之路(九)购物车实例

  • Post author:
  • Post category:java


eclipse如何配置此文档的页面属性?


window–>preferences–>General–>Appearance


1、搭建开发环境

1.1 导入开发包

jstl开发包

1.2 创建组织程序的包

cn.itcast.db(代表数据库)

cn.itcast.daomain(封转数据的实体)

cn.itcast.dao(操作数据库,数据访问对象,增删改查)

cn.itcast.service(调dao,统一对web层提供业务服务)

cn.itcast.web.controller(servlet响应客户端的请求)

cn.itcast.web.UI(提供用户界面)

cn.itcast.utils()

WEB-INF/jsp保存网站jsp

1.3 创建代表数据库的DB

2.开发dao

3.开发service

4.开发web

第一步、DB.java

package cn.itcast.db;
import *;
public class DB {
    private static Map map=new LinkedHashMap();
    static{
        map.put("1", new Book("1","javaweb开发","老张",39,"一本好书"));
        map.put("2", new Book("2","jdbc开发","黎活明",39,"一本好书"));
        map.put("3", new Book("3","javascript开发","方立勋",39,"一本好书"));
        map.put("4", new Book("4","EJB开发","杨中科",39,"一本好书"));
        map.put("5", new Book("5","J2EE开发","毕福剑",39,"一本好书"));
        map.put("6", new Book("6","Spring开发","刘道成",39,"一本好书"));
    }
    public static Map getAll(){
        return map;
    }
}

第1.5步、Book.java

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;
    }
}

第二步、BookDao.java

package cn.itcast.dao;
import *;
public class BookDao {
    public Map getAll(){   
        return DB.getAll(); 
    }
    public Book find(String id){
        return (Book)DB.getAll().get(id);
    }
}

第三步、BusinessService.java

package cn.itcast.service;
import *;
//业务类,统一对web层提供所有服务
public class BusinessService {
    private BookDao dao=new BookDao();
    public Map getAllBook(){
        return dao.getAll();
    }
    public Book findBook(String id){
        return dao.find(id);
    }
    //删除购物车中的购物项
    public void deleteCartItem(String id, Cart cart) {
        cart.getMap().remove(id);

    }
    public void clearCart(Cart cart) {
        cart.getMap().clear();

    }
    public void changeItemQuantity(String id, String quantity, Cart cart) {
        CartItem item=cart.getMap().get(id);
        item.setQuantity(Integer.parseInt(quantity));
    }

}

第四步、index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   <title>首页</title>
  </head>

  <body>
    <a href="${pageContext.request.contextPath}/servlet/ListBook">浏览书籍</a>
  </body>
</html>

第五步、ListBook.java

package cn.itcast.web.controller;
import *;
//获取所有书
public class ListBook extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        BusinessService service=new BusinessService();
        Map map=service.getAllBook();
        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);
    }

}

第六步、listBook.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">
  <h1>书籍列表</h1>
    <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>

第七步、BuyServlet.java

package cn.itcast.web.controller;
import *;
//完成书籍购买
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.findBook(id);
        //得到用户的购物车
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        if(cart==null){
            cart=new Cart();
            request.getSession().setAttribute("cart", cart);
        }
        //把书加到用户购物车中,完成购买
        cart.add(book);
        request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

第八步、Cart.java

package cn.itcast.domain;
import *;
//代表用户的购物车
public class Cart {
    private Map<String,CartItem> map=new LinkedHashMap();
    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{
            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() {
        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.java

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;
    }
}

第十步、ListCartUIServlet.java

package cn.itcast.web.UI;
import *;
public class ListCartUIServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/liscart.jsp").forward(request, response);
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

第十一步、listcart.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">
      function deleteitem(id){
       if(window.confirm("您确定要删除吗?")){
         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"
          }
      }
      //前台校验了,后台也要校验,因为用户可能禁用javascript
      function changeQuantity(input,id,oldvalue){
         var quantity=input.value;//得到要修改的数量
         //检查用户输入的熟练刚是不是一个数字(注意下面的判断语句)
         //检查用户输入的数量是不是一个整数
         if(quantity<0 || quantity!=parseInt(quantity)){
             alert("请输入一个正整数!");
             input.value=oldvalue;
             return;
         }
         var b=window.confirm("您确定把书的数量修改为"+quantity+"吗?");
         if(b){
            window.location.href="${pageContext.request.contextPath}/servlet/ChangeQuatityServlet?id="+id+"&quantity="+quantity;
         }
      }
    </script>
  </head>
  <body style="text-align:center">
  <h1>购物车列表</h1>
  <c:if test="${empty(cart.map)}"><%--判断map是否为null"" --%>
    您没有购买任何商品!!! 
  </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 type="text" name="quantity" value="${entry.value.quantity }" style="width:35px" onchange=
"changeQuantity(this,${entry.key},${entry.value.quantity })">
                </td>
                <td>${entry.value.price }</td>
                <td> 
                    <a href="#" onclick="deleteitem(${entry.key});return false;">删除</a>
                </td>

        </tr>
        </c:forEach>
        <tr>
            <td colspan="3">总价</td>
            <td colspan="2">${cart.price }元</td>
            <td colspan="1">
                 <a href="#" onclick="clearcart();return false;">清空购物车</a>
                 <%--注意这里的return false;表示清除浏览器的默认行为 --%>
            </td>
        </tr>

    </table>
   </c:if>
  </body>
</html>

第十二步、DeleteItemServlet.java

package cn.itcast.web.controller;
import *;
//删除指定的购物项
public class DeleteItemServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id=request.getParameter("id");
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        BusinessService service=new BusinessService();
        service.deleteCartItem(id,cart);
        //删除成功
        request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

第十三步、ClearCartServlet.java

package cn.itcast.web.controller;
import *;
//清空购物车
public class ClearCartServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Cart cart=(Cart) request.getSession().getAttribute("cart");
        BusinessService service=new BusinessService();
        service.clearCart(cart);
        request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

第十四步、ChangeQuatityServlet.java

package cn.itcast.web.controller;
import *;
//吧购物车中的书修改为指定数量
public class ChangeQuatityServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String id=request.getParameter("id");
        String quantity=request.getParameter("quantity");
        Cart cart=(Cart)request.getSession().getAttribute("cart");
        BusinessService service=new BusinessService();
        service.changeItemQuantity(id,quantity,cart);
        request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}



版权声明:本文为fandong12388原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。