重新编辑后源码压缩包上传至码云,地址:
https://gitee.com/lhw1320/codes/d4bkq1rp97uc2venfz3lw79
项目概述
前面的时候我写过一个商品浏记录的小例子,这一次我们使用实现购物车效果。前面的例子是:
http://blog.csdn.net/erlian1992/article/details/52047258。这一次在此基础上来采用的是MVC三层模型实现
(JSP+Servlet+dao)来实现这个小项目。
三层架构:
JSP视图层
Servlet控制层
dao模型层
DB数据库层
编码实现:
首先先来数据库脚本items.sql:
/*
Navicat MySQL Data Transfer
Source Server : MySQL50
Source Server Version : 50067
Source Host : localhost:3306
Source Database : shopping
Target Server Type : MYSQL
Target Server Version : 50067
File Encoding : 65001
Date: 2016-08-01 12:12:31
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for items
-- ----------------------------
DROP TABLE IF EXISTS `items`;
CREATE TABLE `items` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(50) default NULL,
`city` varchar(50) default NULL,
`price` int(11) default NULL,
`number` int(11) default NULL,
`picture` varchar(500) default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of items
-- ----------------------------
INSERT INTO `items` VALUES ('1', '沃特篮球鞋', '佛山', '180', '500', '001.jpg');
INSERT INTO `items` VALUES ('2', '安踏运动鞋', '福州', '120', '800', '002.jpg');
INSERT INTO `items` VALUES ('3', '耐克运动鞋', '广州', '500', '1000', '003.jpg');
INSERT INTO `items` VALUES ('4', '阿迪达斯T血衫', '上海', '388', '600', '004.jpg');
INSERT INTO `items` VALUES ('5', '李宁文化衫', '广州', '180', '900', '005.jpg');
INSERT INTO `items` VALUES ('6', '小米3', '北京', '1999', '3000', '006.jpg');
INSERT INTO `items` VALUES ('7', '小米2S', '北京', '1299', '1000', '007.jpg');
INSERT INTO `items` VALUES ('8', 'thinkpad笔记本', '北京', '6999', '500', '008.jpg');
INSERT INTO `items` VALUES ('9', 'dell笔记本', '北京', '3999', '500', '009.jpg');
INSERT INTO `items` VALUES ('10', 'ipad5', '北京', '5999', '500', '010.jpg');
我们再来连接MySQL数据库工具类DBHelper
:
package com.util;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* 连接MySQL数据库工具类
* @author Administrator
* @date 2016年08月01日
*/
public class DBHelper {
//数据库驱动
private static final String driver = "com.mysql.jdbc.Driver";
//连接数据库的URL地址
private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8";
//数据库的用户名
private static final String username="root";
//数据库的密码
private static final String password="root";
//Connection连接对象conn
private static Connection conn=null;
//静态代码块负责加载驱动
static {
try{
Class.forName(driver);
}catch(Exception e){
e.printStackTrace();
}
}
//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception{
if(conn==null){
conn = DriverManager.getConnection(url, username, password);
return conn;
}else{
return conn;
}
}
public static void main(String[] args) {
//测试数据库是否连接正常
try{
Connection conn = DBHelper.getConnection();
if(conn!=null){
System.out.println("数据库连接正常!");
}else{
System.out.println("数据库连接异常!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
//数据库驱动
private static final String driver = "com.mysql.jdbc.Driver";
//连接数据库的URL地址
private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8";
//数据库的用户名
private static final String username="root";
//数据库的密码
private static final String password="root";
//Connection连接对象conn
private static Connection conn=null;
//静态代码块负责加载驱动
static {
try{
Class.forName(driver);
}catch(Exception e){
e.printStackTrace();
}
}
//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception{
if(conn==null){
conn = DriverManager.getConnection(url, username, password);
return conn;
}else{
return conn;
}
}
public static void main(String[] args) {
//测试数据库是否连接正常
try{
Connection conn = DBHelper.getConnection();
if(conn!=null){
System.out.println("数据库连接正常!");
}else{
System.out.println("数据库连接异常!");
}
}catch(Exception e){
e.printStackTrace();
}
}
}
再来创建两个实体类,一个是对应items数据表的Items.java
package com.entity;
/**
* 商品实体类
* @author Administrator
* @date 2016年08月01日
*/
public class Items {
private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片
//保留此不带参数的构造方法
public Items(){
}
//不带参数的构造方法
public Items(int id,String name,String city,int price,int number,String picture){
this.id = id;
this.name = name;
this.city = city;
this.picture = picture;
this.price = price;
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
@Override
public int hashCode() {
return this.getId()+this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj instanceof Items){
Items i = (Items)obj;
if(this.getId()==i.getId()&&this.getName().equals(i.getName())){
return true;
}else{
return false;
}
}else{
return false;
}
}
@Override
public String toString(){
return "商品编号:"+this.getId()+",商品名称:"+this.getName();
}
}
private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片
//保留此不带参数的构造方法
public Items(){
}
//不带参数的构造方法
public Items(int id,String name,String city,int price,int number,String picture){
this.id = id;
this.name = name;
this.city = city;
this.picture = picture;
this.price = price;
this.number = number;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
@Override
public int hashCode() {
return this.getId()+this.getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(obj instanceof Items){
Items i = (Items)obj;
if(this.getId()==i.getId()&&this.getName().equals(i.getName())){
return true;
}else{
return false;
}
}else{
return false;
}
}
@Override
public String toString(){
return "商品编号:"+this.getId()+",商品名称:"+this.getName();
}
}
一个是Cart.java
package com.entity;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 购物车实体类(添加、删除和计算价格)
* @author Administrator
* @date 2016年08月01日
*/
public class Cart {
//购买商品的集合
private HashMap<Items,Integer> goods;
//购物车的总金额
private double totalPrice;
//构造方法
public Cart(){
goods = new HashMap<Items,Integer>();
totalPrice = 0.0;
}
public HashMap<Items, Integer> getGoods() {
return goods;
}
public void setGoods(HashMap<Items, Integer> goods) {
this.goods = goods;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
//添加商品进购物车的方法
public boolean addGoodsInCart(Items item ,int number){
if(goods.containsKey(item)){
goods.put(item, goods.get(item)+number);
}else{
goods.put(item, number);
}
calTotalPrice(); //重新计算购物车的总金额
return true;
}
//删除商品的方法
public boolean removeGoodsFromCart(Items item){
goods.remove(item);
calTotalPrice(); //重新计算购物车的总金额
return true;
}
//统计购物车的总金额
public double calTotalPrice(){
double sum = 0.0;
Set<Items> keys = goods.keySet(); //获得键的集合
Iterator<Items> it = keys.iterator(); //获得迭代器对象
while(it.hasNext()){
Items i = it.next();
sum += i.getPrice()* goods.get(i);
}
this.setTotalPrice(sum); //设置购物车的总金额
return this.getTotalPrice();
}
public static void main(String[] args) {
//先创建两个商品对象
Items i1 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg");
Items i2 = new Items(2,"李宁运动鞋","广州",300,500,"002.jpg");
Items i3 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg");
Cart cart = new Cart();
cart.addGoodsInCart(i1, 1);
cart.addGoodsInCart(i2, 2);
//再次购买沃特篮球鞋,购买3双
cart.addGoodsInCart(i3, 3);
//遍历购物车商品的集合
Set<Map.Entry<Items, Integer>> items= cart.getGoods().entrySet();
for(Map.Entry<Items, Integer> obj:items){
System.out.println(obj);
}
System.out.println("购物车的总金额:"+cart.getTotalPrice());
}
}
//购买商品的集合
private HashMap<Items,Integer> goods;
//购物车的总金额
private double totalPrice;
//构造方法
public Cart(){
goods = new HashMap<Items,Integer>();
totalPrice = 0.0;
}
public HashMap<Items, Integer> getGoods() {
return goods;
}
public void setGoods(HashMap<Items, Integer> goods) {
this.goods = goods;
}
public double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(double totalPrice) {
this.totalPrice = totalPrice;
}
//添加商品进购物车的方法
public boolean addGoodsInCart(Items item ,int number){
if(goods.containsKey(item)){
goods.put(item, goods.get(item)+number);
}else{
goods.put(item, number);
}
calTotalPrice(); //重新计算购物车的总金额
return true;
}
//删除商品的方法
public boolean removeGoodsFromCart(Items item){
goods.remove(item);
calTotalPrice(); //重新计算购物车的总金额
return true;
}
//统计购物车的总金额
public double calTotalPrice(){
double sum = 0.0;
Set<Items> keys = goods.keySet(); //获得键的集合
Iterator<Items> it = keys.iterator(); //获得迭代器对象
while(it.hasNext()){
Items i = it.next();
sum += i.getPrice()* goods.get(i);
}
this.setTotalPrice(sum); //设置购物车的总金额
return this.getTotalPrice();
}
public static void main(String[] args) {
//先创建两个商品对象
Items i1 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg");
Items i2 = new Items(2,"李宁运动鞋","广州",300,500,"002.jpg");
Items i3 = new Items(1,"沃特篮球鞋","温州",200,500,"001.jpg");
Cart cart = new Cart();
cart.addGoodsInCart(i1, 1);
cart.addGoodsInCart(i2, 2);
//再次购买沃特篮球鞋,购买3双
cart.addGoodsInCart(i3, 3);
//遍历购物车商品的集合
Set<Map.Entry<Items, Integer>> items= cart.getGoods().entrySet();
for(Map.Entry<Items, Integer> obj:items){
System.out.println(obj);
}
System.out.println("购物车的总金额:"+cart.getTotalPrice());
}
}
接下来是dao层ItemsDAO.java
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.util.DBHelper;
import com.entity.Items;
/**
* 商品的业务逻辑类
* @author Administrator
* @date 2016年08月01日
*/
public class ItemsDAO {
// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;//数据库连接对象
PreparedStatement stmt = null;//SQL语句对象
ResultSet rs = null;//数据集对象
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DBHelper.getConnection();
String sql = "select * from items;"; // 查询SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();//获取数据集
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// 把一个商品加入集合
}
return list; // 返回集合。
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 释放SQL语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// 根据商品编号ID获得商品详细资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from items where id=?;"; // SQL查询语句
stmt = conn.prepareStatement(sql);
//把id的值赋给SQL查询语句中第一个问号
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//获取最近浏览的前五条商品信息
public ArrayList<Items> getViewList(String list){
System.out.println("list:"+list);
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount=5; //每次返回前五条记录
if(list!=null&&list.length()>0){
String[] arr = list.split(",");
System.out.println("arr.length="+arr.length);
//如果商品记录大于等于5条
if(arr.length>=5){
for(int i=arr.length-1;i>=arr.length-iCount;i--){
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}else{
for(int i=arr.length-1;i>=0;i--){
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}else{
return null;
}
}
}
// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;//数据库连接对象
PreparedStatement stmt = null;//SQL语句对象
ResultSet rs = null;//数据集对象
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DBHelper.getConnection();
String sql = "select * from items;"; // 查询SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();//获取数据集
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// 把一个商品加入集合
}
return list; // 返回集合。
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 释放SQL语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// 根据商品编号ID获得商品详细资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from items where id=?;"; // SQL查询语句
stmt = conn.prepareStatement(sql);
//把id的值赋给SQL查询语句中第一个问号
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//获取最近浏览的前五条商品信息
public ArrayList<Items> getViewList(String list){
System.out.println("list:"+list);
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount=5; //每次返回前五条记录
if(list!=null&&list.length()>0){
String[] arr = list.split(",");
System.out.println("arr.length="+arr.length);
//如果商品记录大于等于5条
if(arr.length>=5){
for(int i=arr.length-1;i>=arr.length-iCount;i--){
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}else{
for(int i=arr.length-1;i>=0;i--){
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}else{
return null;
}
}
}
最后是Servlet控制层中的CartServlet:
package com.servlet;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.dao.ItemsDAO;
import com.entity.Cart;
import com.entity.Items;
/**
* Servlet implementation class CarServlet
*/
@WebServlet(name="CartServlet" ,urlPatterns={"/CartServlet"})
public class CartServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String action;//表示购物车动作:add,show,delete
private ItemsDAO idao = new ItemsDAO();//商品业务逻辑类对象
/**
* @see HttpServlet#HttpServlet()
*/
public CartServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
if(request.getParameter("action")!=null){
this.action = request.getParameter("action");
//添加商品进购物车
if(action.equals("add")) {
if(addToCart(request,response)){
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/failure.jsp").forward(request, response);
}
}
//显示购物车
if(action.equals("show")){
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
//如果是执行删除购物车中的商品
if(action.equals("delete")) {
if(deleteFromCart(request,response)){
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
}
}
//添加商品进购物车的方法
private boolean addToCart(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
String number = request.getParameter("num");
Items item = idao.getItemsById(Integer.parseInt(id));
//是否是第一次给购物车添加商品,需要给session中创建一个新的购物车对象
if(request.getSession().getAttribute("cart") == null){
Cart cart = new Cart();
request.getSession().setAttribute("cart",cart);
}
//不是第一次添加进购物车
Cart cart = (Cart)request.getSession().getAttribute("cart");
if(cart.addGoodsInCart(item, Integer.parseInt(number))){
return true;
}else{
return false;
}
}
//从购物车中删除商品
private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
Cart cart = (Cart)request.getSession().getAttribute("cart");
Items item = idao.getItemsById(Integer.parseInt(id));
if(cart.removeGoodsFromCart(item)){
return true;
}else{
return false;
}
}
}
private static final long serialVersionUID = 1L;
private String action;//表示购物车动作:add,show,delete
private ItemsDAO idao = new ItemsDAO();//商品业务逻辑类对象
/**
* @see HttpServlet#HttpServlet()
*/
public CartServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=UTF-8");
//PrintWriter out = response.getWriter();
if(request.getParameter("action")!=null){
this.action = request.getParameter("action");
//添加商品进购物车
if(action.equals("add")) {
if(addToCart(request,response)){
request.getRequestDispatcher("/success.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/failure.jsp").forward(request, response);
}
}
//显示购物车
if(action.equals("show")){
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
//如果是执行删除购物车中的商品
if(action.equals("delete")) {
if(deleteFromCart(request,response)){
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}else{
request.getRequestDispatcher("/cart.jsp").forward(request, response);
}
}
}
}
//添加商品进购物车的方法
private boolean addToCart(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
String number = request.getParameter("num");
Items item = idao.getItemsById(Integer.parseInt(id));
//是否是第一次给购物车添加商品,需要给session中创建一个新的购物车对象
if(request.getSession().getAttribute("cart") == null){
Cart cart = new Cart();
request.getSession().setAttribute("cart",cart);
}
//不是第一次添加进购物车
Cart cart = (Cart)request.getSession().getAttribute("cart");
if(cart.addGoodsInCart(item, Integer.parseInt(number))){
return true;
}else{
return false;
}
}
//从购物车中删除商品
private boolean deleteFromCart(HttpServletRequest request, HttpServletResponse response){
String id = request.getParameter("id");
Cart cart = (Cart)request.getSession().getAttribute("cart");
Items item = idao.getItemsById(Integer.parseInt(id));
if(cart.removeGoodsFromCart(item)){
return true;
}else{
return false;
}
}
}
再来视图层:
商品列表页面index.jsp
<%@page import="com.entity.Items"%>
<%@page import="com.dao.ItemsDAO"%>
<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品列表页面</title>
<style type="text/css">
hr{
border-color:FF7F00;
}
div{
float:left;
margin: 10px;
}
div dd{
margin:0px;
font-size:10pt;
}
div dd.dd_name{
color:blue;
}
div dd.dd_city{
color:#000;
}
</style>
</head>
<body>
<h1>商品展示</h1>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>
<!-- 商品循环开始 -->
<%
//防止中文乱码
request.setCharacterEncoding("UTF-8");
ItemsDAO itemsDao = new ItemsDAO();
ArrayList<Items> list = itemsDao.getAllItems();
if(list!=null&&list.size()>0){
for(int i=0;i<list.size();i++){
Items item = list.get(i);
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=item.getId()%>">
<img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/>
</a>
</dt>
<dd class="dd_name"><%=item.getName() %></dd>
<dd class="dd_city">产地:<%=item.getCity() %> 价格:¥ <%=item.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->
<%
}
}
%>
</td>
</tr>
</table>
</center>
</body>
</html>
for(int i=0;i<list.size();i++){
Items item = list.get(i);
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=item.getId()%>">
<img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/>
</a>
</dt>
<dd class="dd_name"><%=item.getName() %></dd>
<dd class="dd_city">产地:<%=item.getCity() %> 价格:¥ <%=item.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->
<%
}
}
%>
</td>
</tr>
</table>
</center>
</body>
</html>
商品详情页面details.jsp
<%@page import="java.util.ArrayList"%>
<%@ page import="com.entity.Items"%>
<%@ page import="com.dao.ItemsDAO"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>商品详情页面</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/lhgcore.js"></script>
<script type="text/javascript" src="js/lhgdialog.js"></script>
<script type="text/javascript">
function selflog_show(id){
var num = document.getElementById("number").value;
J.dialog.get({id: 'haoyue_creat',title: '购物成功',width: 600,height:400, link: '<%=path%>/CartServlet?id='+id+'&num='+num+'&action=add', cover:true});
}
//商品数量增加
function add() {
var num = parseInt(document.getElementById("number").value);
if (num < 100) {
document.getElementById("number").value = ++num;
}
}
//商品数量减少
function sub() {
var num = parseInt(document.getElementById("number").value);
if (num > 1) {
document.getElementById("number").value = --num;
}
}
</script>
<style type="text/css">
hr {
border-color: FF7F00;
}
div {
float: left;
margin-left: 30px;
margin-right: 30px;
margin-top: 5px;
margin-bottom: 5px;
}
div dd {
margin: 0px;
font-size: 10pt;
}
div dd.dd_name {
color: blue;
}
div dd.dd_city {
color: #000;
}
div #cart {
margin: 0px auto;
text-align: right;
}
span {
padding: 0 2px;
border: 1px #c0c0c0 solid;
cursor: pointer;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<h1>商品详情</h1>
<a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- 商品详情 -->
<%
ItemsDAO itemDao = new ItemsDAO();
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if(item != null){
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
</tr>
<tr>
<td><B><%=item.getName() %></B></td>
</tr>
<tr>
<td>产地:<%=item.getCity()%></td>
</tr>
<tr>
<td>价格:<%=item.getPrice() %>¥</td>
</tr>
<tr>
<td>购买数量:
<span id="sub" onclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2" /><span id="add" onclick="add();">+</span>
</td>
</tr>
</table>
<div id="cart">
<img src="images/buy_now.png" />
<a href="javascript:selflog_show(<%=item.getId()%>)"><img src="images/in_cart.png" /></a>
<a href="CartServlet?action=show"><img src="images/view_cart.jpg" /></a>
</div>
</td>
<%
}
%>
<%
String list ="";
//从客户端获得Cookies集合
Cookie[] cookies = request.getCookies();
//遍历这个Cookies集合
if(cookies != null&&cookies.length > 0){
for(Cookie c:cookies){
if(c.getName().equals("ListViewCookie")){
list = c.getValue();
}
}
}
//追加商品编号
list += request.getParameter("id")+",";
//如果浏览记录超过1000条,清零.
String[] arr = list.split(",");
if(arr != null&&arr.length > 0){
if(arr.length>=1000){
list = "";
}
}
Cookie cookie = new Cookie("ListViewCookie",list);
response.addCookie(cookie);
%>
<!-- 浏览过的商品 -->
<td width="30%" bgcolor="#EEE" align="center">
<br>
<b>您浏览过的商品</b><br>
<!-- 循环开始 -->
<%
ArrayList<Items> itemlist = itemDao.getViewList(list);
if(itemlist!=null&&itemlist.size()>0 ){
System.out.println("itemlist.size="+itemlist.size());
for(Items i:itemlist){
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=i.getName() %></dd>
<dd class="dd_city">产地:<%=i.getCity() %> 价格:<%=i.getPrice() %> ¥ </dd>
</dl>
</div>
<%
}
}
%>
<!-- 循环结束 -->
</td>
</tr>
</table>
</center>
</body>
</html>
function add() {
var num = parseInt(document.getElementById("number").value);
if (num < 100) {
document.getElementById("number").value = ++num;
}
}
//商品数量减少
function sub() {
var num = parseInt(document.getElementById("number").value);
if (num > 1) {
document.getElementById("number").value = --num;
}
}
</script>
<style type="text/css">
hr {
border-color: FF7F00;
}
div {
float: left;
margin-left: 30px;
margin-right: 30px;
margin-top: 5px;
margin-bottom: 5px;
}
div dd {
margin: 0px;
font-size: 10pt;
}
div dd.dd_name {
color: blue;
}
div dd.dd_city {
color: #000;
}
div #cart {
margin: 0px auto;
text-align: right;
}
span {
padding: 0 2px;
border: 1px #c0c0c0 solid;
cursor: pointer;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<h1>商品详情</h1>
<a href="index.jsp">首页</a> >> <a href="index.jsp">商品列表</a>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- 商品详情 -->
<%
ItemsDAO itemDao = new ItemsDAO();
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if(item != null){
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
</tr>
<tr>
<td><B><%=item.getName() %></B></td>
</tr>
<tr>
<td>产地:<%=item.getCity()%></td>
</tr>
<tr>
<td>价格:<%=item.getPrice() %>¥</td>
</tr>
<tr>
<td>购买数量:
<span id="sub" οnclick="sub();">-</span><input type="text" id="number" name="number" value="1" size="2" /><span id="add" οnclick="add();">+</span>
</td>
</tr>
</table>
<div id="cart">
<img src="images/buy_now.png" />
<a href="javascript:selflog_show(<%=item.getId()%>)"><img src="images/in_cart.png" /></a>
<a href="CartServlet?action=show"><img src="images/view_cart.jpg" /></a>
</div>
</td>
<%
}
%>
<%
String list ="";
//从客户端获得Cookies集合
Cookie[] cookies = request.getCookies();
//遍历这个Cookies集合
if(cookies != null&&cookies.length > 0){
for(Cookie c:cookies){
if(c.getName().equals("ListViewCookie")){
list = c.getValue();
}
}
}
//追加商品编号
list += request.getParameter("id")+",";
//如果浏览记录超过1000条,清零.
String[] arr = list.split(",");
if(arr != null&&arr.length > 0){
if(arr.length>=1000){
list = "";
}
}
Cookie cookie = new Cookie("ListViewCookie",list);
response.addCookie(cookie);
%>
<!-- 浏览过的商品 -->
<td width="30%" bgcolor="#EEE" align="center">
<br>
<b>您浏览过的商品</b><br>
<!-- 循环开始 -->
<%
ArrayList<Items> itemlist = itemDao.getViewList(list);
if(itemlist!=null&&itemlist.size()>0 ){
System.out.println("itemlist.size="+itemlist.size());
for(Items i:itemlist){
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=i.getName() %></dd>
<dd class="dd_city">产地:<%=i.getCity() %> 价格:<%=i.getPrice() %> ¥ </dd>
</dl>
</div>
<%
}
}
%>
<!-- 循环结束 -->
</td>
</tr>
</table>
</center>
</body>
</html>
购买成功页面success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>购买成功页面</title>
</head>
<body>
<center>
<img src="images/add_cart_success.jpg"/>
<hr>
<%
String id = request.getParameter("id");
String num = request.getParameter("num");
%>
您成功购买了<%=num %>件商品编号为<%=id %>的商品
<br>
<br>
<br>
</center>
</body>
</html>
购买失败页面failure.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>购买失败页面</title>
</head>
<body>
<center>
<img src="images/add_cart_failure.jpg"/>
<hr>
<br>
<br>
<br>
</center>
</body>
</html>
购物车页面cart.jsp
<%@page import="java.util.Iterator"%>
<%@page import="java.util.Set"%>
<%@page import="com.entity.Items"%>
<%@page import="java.util.HashMap"%>
<%@page import="com.entity.Cart"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>购物车页面</title>
<link type="text/css" rel="stylesheet" href="css/style1.css" />
<script type="text/javascript">
function delcfm() {
if (!confirm("确认要删除?")) {
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<h1>我的购物车</h1>
<a href="index.jsp">首页</a> >>
<a href="index.jsp">商品列表</a>
<hr>
<div id="shopping">
<form action="#" method="post">
<table>
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<%
//首先判断session中是否有购物车对象
if(request.getSession().getAttribute("cart")!=null){
%>
<!-- 循环的开始 -->
<%
Cart cart = (Cart)request.getSession().getAttribute("cart");
HashMap<Items,Integer> goods = cart.getGoods();
Set<Items> items = goods.keySet();
Iterator<Items> it = items.iterator();
while(it.hasNext()){
Items i = it.next();
%>
<tr name="products" id="product_id_1">
<td class="thumb">
<img src="images/<%=i.getPicture()%>" />
<a href=""><%=i.getName()%></a>
</td>
<td class="number"><%=i.getPrice() %></td>
<td class="price" id="price_id_1">
<span><%=i.getPrice()*goods.get(i) %></span>
<input type="hidden" value="" />
</td>
<td class="number"><%=goods.get(i)%></td>
<td class="delete"><a href="CartServlet?action=delete&id=<%=i.getId()%>" onclick="delcfm();">删除</a></td>
</tr>
<%
}
%>
<!--循环的结束-->
</table>
<div class="total">
<span id="total">总计:<%=cart.getTotalPrice() %>¥</span>
</div>
<%
}
%>
<div class="button">
<input type="submit" value="" />
</div>
</form>
</div>
</body>
</html>
function delcfm() {
if (!confirm("确认要删除?")) {
window.event.returnValue = false;
}
}
</script>
</head>
<body>
<h1>我的购物车</h1>
<a href="index.jsp">首页</a> >>
<a href="index.jsp">商品列表</a>
<hr>
<div id="shopping">
<form action="#" method="post">
<table>
<tr>
<th>商品名称</th>
<th>商品单价</th>
<th>商品价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
<%
//首先判断session中是否有购物车对象
if(request.getSession().getAttribute("cart")!=null){
%>
<!-- 循环的开始 -->
<%
Cart cart = (Cart)request.getSession().getAttribute("cart");
HashMap<Items,Integer> goods = cart.getGoods();
Set<Items> items = goods.keySet();
Iterator<Items> it = items.iterator();
while(it.hasNext()){
Items i = it.next();
%>
<tr name="products" id="product_id_1">
<td class="thumb">
<img src="images/<%=i.getPicture()%>" />
<a href=""><%=i.getName()%></a>
</td>
<td class="number"><%=i.getPrice() %></td>
<td class="price" id="price_id_1">
<span><%=i.getPrice()*goods.get(i) %></span>
<input type="hidden" value="" />
</td>
<td class="number"><%=goods.get(i)%></td>
<td class="delete"><a href="CartServlet?action=delete&id=<%=i.getId()%>" οnclick="delcfm();">删除</a></td>
</tr>
<%
}
%>
<!--循环的结束-->
</table>
<div class="total">
<span id="total">总计:<%=cart.getTotalPrice() %>¥</span>
</div>
<%
}
%>
<div class="button">
<input type="submit" value="" />
</div>
</form>
</div>
</body>
</html>
项目运行结果:
商品列表:
选择一个商品进入商品详情:
选择好数量,加入到购物车中:
查看购物车:
针对很多人要源码,我把源码上传了到CSDN上,大家自己下载,工作了有时候回复不及时。本来想要直接分
享的,可是最低需要设置一个积分,没办法,以后代码会放在GITHUB上。
地址:https://download.csdn.net/download/erlian1992/10393969