javaweb购物车案列学习开发

本文实例为大家分享了javaweb购物车案列的具体代码,供大家参考,具体内容如下

一、项目目录结构  

 

二、源代码

dao包——dao层:BookDao.java

package com.dao;

import java.util.Map;
import com.DB.DB;
import com.domain.Book;

public class BookDao {

 public Map getAll(){
 return DB.getAll();
 }

 public Book find(String id){
 return (Book) DB.getAll().get(id);
 }
} 

DB包:DB.java——模拟数据库

package com.DB;
import java.util.LinkedHashMap;
import java.util.Map;
import com.domain.Book;
import com.sun.org.apache.bcel.internal.generic.NEW;
//代表数据库
//代表数据库
public class DB {

 private static Map map = new LinkedHashMap();
 static{
 map.put("1", new Book("1","javaweb开发","老张",38,"一本好书"));
 map.put("2", new Book("2","jdbc开发","老黎",18,"一本好书"));
 map.put("3", new Book("3","ajax开发","老佟",328,"一本好书"));
 map.put("4", new Book("4","jbpm开发","老毕",58,"一本好书"));
 map.put("5", new Book("5","struts开发","老方",28,"一本好书"));
 map.put("6", new Book("6","spring开发","老方",98,"一本好书"));
 }

 public static Map getAll(){
 return map;
 }

}

domain包:

Book.java:书的实体类

package com.domain;
//书的实体类
public class Book {
 private String id;
 private String name;
 private String author;
 private double price;
 private String description;

 public Book() {
 super();
 // TODO Auto-generated constructor stub
 }
 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.java:购物车类    

package com.domain;

import java.util.LinkedHashMap;
import java.util.Map;

//代表用户的购物车

//代表用户的购物车
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 com.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;
 }

}

service包:service层

BusinessService.java:      

package com.service;

import java.util.Map;

import com.dao.BookDao;
import com.domain.Book;
import com.domain.Cart;
import com.domain.CartItem;
//业务类,统一对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));
 }

}

web层:

ListBookServlet.java:显示所有书籍      

package com.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.service.BusinessService;
//获取所有书籍
//获取所有书
public class ListBookServlet 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);
 }

}

BuyServlet.java:处理购买请求      

package com.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 com.domain.Book;
import com.domain.Cart;
import com.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.findBook(id);

 //得到用户的购物车
 Cart cart = (Cart) request.getSession().getAttribute("cart");
 if(cart==null){
  cart = new Cart();
  request.getSession().setAttribute("cart", cart);
 }

 //把书加到用户购物车中,完成购买
 cart.add(book);

 //response.sendRedirect("/WEB-INF/jsp/listcart.jsp");
 request.getRequestDispatcher("/WEB-INF/jsp/listcart.jsp").forward(request, response);

 }

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

} 

DeleteItemServlet.java:删除某一种商品

package com.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 com.domain.Cart;
import com.service.BusinessService;
//删除指定的购物项
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 com.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.domain.Cart;
import com.service.BusinessService;
//清空购物车
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);
 }

}

ChangeQuantityServlet.java:修改购物车中指定商品的数量

package com.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.domain.Cart;
import com.service.BusinessService;

//把购物车中的书修改为指定数量
public class ChangeQuantityServlet 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);
 }

}

 jsp页面: 

WebRoot/WEB-INF/jsp/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 }" rel="external nofollow" target="_blank">购买</a>
  </td>
  </tr>
 </c:forEach>
 </table>

</body>

WebRoot/WEB-INF/jsp/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){
  var b = window.confirm("您确认删除吗??");
  if(b){
  window.location.href="${pageContext.request.contextPath }/servlet/DeleteItemServlet?id=" rel="external nofollow" +id;
  }
 }

 function clearcart(){
  var b = window.confirm("您确认清空吗??");
  if(b){
  window.location.href="${pageContext.request.contextPath}/servlet/ClearCartServlet" rel="external nofollow" ;
  }
 }

 function changeQuantity(input,id,oldvalue){
  var quantity = input.value; //得到要修改的数量 sdfsfs

  /*
  //检查用户输入的数量是不是一个数字
  if(isNaN(quantity)){
  alert("请输入数字!!");
  input.value = oldvalue;
  return;
  }
  */

  //检查用户输入的数量是不是一个正整数
  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/ChangeQuantityServlet?id=" rel="external nofollow" + id + "&quantity=" + quantity;
  }
 }
 </script>

 </head>

 <body style="text-align: center">

 <h1>购物车列表</h1>

 <c:if test="${empty(cart.map)}">
 您没有购买任何商品!!!
 </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="javascript:void(0)" rel="external nofollow" rel="external nofollow" onclick="deleteitem(${entry.key })">删除</a> <!-- 去掉超链接默认行为 -->

  </td>
  </tr>
 </c:forEach>

 <tr>
  <td colspan="3">总价</td>
  <td colspan="2">${cart.price }元</td>
  <td colspan="1">
  <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" onclick="clearcart()">清空购物车</a>
  </td>
 </tr>
 </table>
 </c:if>

 </body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • java网上图书商城(4)购物车模块1

    本文实例为大家分享了购物车模块的具体代码,供大家参考,具体内容如下 使用的不是session,也不是cookie,而是表 > 添加购物条目 > 修改购物条目的数量 > 删除条目 > 批量删除条目 > 我的购物车,即按用户查询条目 > 查询勾选的条目 1.数据表 复制代码 代码如下: insert  into `t_cartitem`(`cartItemId`,`quantity`,`bid`,`uid`,`orderBy`) values ('B8939FC551314

  • JAVAEE中用Session简单实现购物车功能示例代码

    Session简单实现购物车功能 这个小程序主要就3个页面,一个商品列表页面(HomeServlet),一个是提示加入购物车页面(AddCartTipServlet),一个是显示购物车清单页面(ShowCartServlet). HomeServlet页面: @WebServlet({ "/HomeServlet", "/home" }) public class HomeServlet extends HttpServlet { private static fi

  • java web开发之购物车功能实现示例代码

    之前没有接触过购物车的东东,也不知道购物车应该怎么做,所以在查询了很多资料,总结一下购物车的功能实现. 查询的资料,找到三种方法: 1.用cookie实现购物车: 2.用session实现购物车: 3.用cookie和数据库(购物车信息持久化)实现购物车: 分析一下这三种方法的优缺点: 1.单纯有cookie实现购物车,这样的购物车不是很理想,设想一下,如果客户端的浏览器把cookie给禁用了,这种方法就会在这里流产- 2.session中保存购物车的信息,这个只是在一个会话中可用,如果用户没有

  • Rxjava+Retrofit+MVP实现购物车功能

    本文实例为大家分享了Rxjava Retrofit实现购物车的具体代码,供大家参考,具体内容如下 效果图: 1.依赖 annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' compile 'com.jakewharton:butterknife:8.8.1' compile 'com.android.support:recyclerview-v7:26.0.0-alpha1' compile 'com.squareup.

  • RxJava+Retrofit+Mvp实现购物车

    本文实例为大家分享了RxJava Retrofit实现购物车展示的具体代码,供大家参考,具体内容如下 先给大家展示一下效果图 框架结构: 1.项目框架:MVP,图片加载用Fresco,网络请求用OKhttp+Retrofit实现(自己封装,加单例模式), 2.完成购物车数据添加(如果接口无数据,可用接口工具添加数据), 3.自定义view实现加减按钮,每次点击加减,item中的总数及总价要做出相应的改变. 4.当数量为1时,点击减号,数量不变,吐司提示用户最小数量为1. 5.底部总数及总价为所有

  • java商城项目实战之购物车功能实现

    本文实例为大家分享了java实现购物车功能的具体代码,供大家参考,具体内容如下 1 需要实现 1.实现淘淘商城的购物车功能 2 购物车功能 2.1 功能说明 1.商品加入购物车时,不是必须要求登录.京东不需要登录,淘宝需要登录.各有好处. 2.计算购物车中商品的总价.当商品数量发生变化时需要重新计算. 3.用户可以删除购物车中的商品. 4.用户下单后,删除购物车的功能. 购物车在用户不登陆的情况下也可以使用购物车.需要把购物车的商品信息写入cookie中.所有对购物车的操作都是操作cookie.

  • java web开发之实现购物车功能

    为了方便自己以后复习,所以写的比较仔细,记录下自己的成长.  既然是做购物车,那么前提条件是首先需要一系列商品,也就是要建一个实体,这里建了一个商品表. 通过查询在浏览器上显示 基本显示已经做好了,现在进入我们的重头戏,Servlet  点击放入购物车时,将访问Servlet 购物车代码 package com.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; im

  • javaweb图书商城设计之购物车模块(3)

    本文继续为大家分享了javaweb图书商城中购物车模块,供大家参考,具体内容如下 购物车存储 保存在session中 保存在cookie中 保存在数据库中 1.创建相关类 购物车的结构: CartItem:购物车条目,包含图书和数量 Cart:购物车,包含一个Map /** * 购物车类 */ public class Cart { private Map<String,CartItem> map = new LinkedHashMap<String,CartItem>(); /*

  • java网上图书商城(5)购物车模块2

    先看看效果: 结算 list.jsp <a href="javascript:jiesuan();" id="jiesuan" class="jiesuan"></a> <form id="jieSuanForm" action="<c:url value='/CartItemServlet'/>" method="post"> <i

  • java实现网上购物车程序

    用java代码写一个简单的网上购物车程序,供大家参考,具体内容如下 需求: 1.写一个商品类,有商品编号.商品名称.商品分类.商品单价属性. 2.写一个商品条目信息类,有商品和数量两个属性,有商品总价格方法. 3.写一个购物车类,有添加商品方法.查看订单信息,删除商品,修改商品,清空购物车,求购物车中所有商品总金额方法.4.写一个测试类,测试上述方法. 商品类: public class Product { private int productId;// 商品编号 private String

随机推荐