MVC购物车项目一

MVC购物车项目一,第1张

实现的功能:
  1. 项目搭建
  2. 登录功能
  3. 页面过滤器
  4. 商品的显示
  5. 购物车商品的增加
  6. 购物车商品的删除
  7. 总价的计算
  8. 清空购物车
  9. 结算界面

⭐项目搭建: 1.数据库 *** 作:
-------------------------------------------------------购物车-----------------------------------------------------
create table car_user
(
    id       number primary key,
    account  varchar2(30) not null,
    password varchar(32)  not null
);

comment on column car_user.ID is '用户编号';
comment on column car_user.account is '用户账户';
comment on column car_user.password is '用户密码(MD5)';

create table car_goods
(
    id       number primary key,
    name     varchar2(20)                        not null,
    describe varchar2(100) default '此商品暂时没有介绍🤣' not null,
    price    number                              not null
);

comment on column car_goods.ID is '商品编号';
comment on column car_goods.name is '商品名称';
comment on column car_goods.describe is '商品描述';
comment on column car_goods.price is '用户价格';

create table car_order
(
    id      number primary key,
    user_id number not null,
    total   number not null
);

comment on column car_order.ID is '订单编号';
comment on column car_order.user_id is '谁的订单!';
comment on column car_order.total is '订单总价';

--订单详情表
create table car_order_item
(
    id       number primary key,
    order_id number not null,
    goods_id number not null,
    quantity number not null,
    total    number not null
);
SELECT * FROM CAR_ORDER_ITEM;

comment on column car_order_item.ID is '订单项编号';
comment on column car_order_item.order_id is '哪个订单!';
comment on column car_order_item.goods_id is '哪个商品!';
comment on column car_order_item.quantity is '下单数量';
comment on column car_order_item.total is '订单项总价';

comment on table car_user is '购物车用户表';
comment on table car_goods is '购物车商品表';
comment on table car_order is '购物车订单表';
comment on table car_order_item is '购物车订单项表';

create unique index car_user_account_idx on car_user (account);

insert into car_user
values (1, '2890@fox.com', 'ff9830c42660c1dd1942844f8069b74a');-- root123

insert into car_user
values (2, '2357@fox.com', 'e10adc3949ba59abbe56e057f20f883e');-- 123456

insert into car_goods
select 1, '丝袜奶茶', '冰冰娘娘,很好喝', 99
from dual
union
select 2, '勃勃奶茶', '啊~,好冰冰', 29
from dual
union
select 3, '蜜雪大补丁', '可以加个桃桃🍑', 59
from dual
union
select 4, '臭🐟咖啡', '人气最高', 88
from dual
union
select 5, '雪王咖啡', 'incredible taste', 999
from dual
union
select 6, '拉稀d筒', '👌,就亿点点', 1
from dual;

insert into car_order_item
values (1, 1, 1, 2, 99 * 2);
insert into car_order_item
values (2, 1, 2, 3, 29 * 3);
insert into car_order_item
values (3, 1, 6, 100, 100);

insert into car_order
values (1, 1, 99 * 2 + 29 * 3 + 100);

insert into car_order_item
values (4, 2, 3, 2, 59 * 2);
insert into car_order_item
values (5, 2, 4, 3, 88 * 3);
insert into car_order_item
values (6, 2, 5, 100, 999 * 100);

insert into car_order
values (2, 2, 59 * 2 + 88 * 3 + 999 * 100);

select * from car_user;
select * from car_order;
select * from car_order_item;
select * from car_goods;
2. 导入jar包:

3.实体类的创建:

(1)user用户实体类:

package com.ljq.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * 用户实体类
 * 
 * @author 一麟
 *
 */

@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class User {

	private Integer id;
	private String account;
	private String password;

}

(2)goods商品实体类:

package com.ljq.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * 商品实体类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class Goods {

	private Integer id;
	private String name;
	private String describe;
	private Integer price;

}

(3)orderItem订单项实体类:

package com.ljq.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

/**
 * 订单实体类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class OrderItem {

	private Integer id;
	private Integer orderId;
	private Goods goods;
	private Integer quantity;
	private Integer total;

}

(4)order.java订单实体类 

package com.ljq.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 订单实体类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Order {

	private Integer id;
	private Integer userId;
	private Integer total;

}
 4.数据库接口创建

(1)IGoodsDao

package com.ljq.dao;

import com.ljq.pojo.Goods;

import java.util.List;

/**
 * 商品 *** 作数据接口
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IGoodsDao {

	List list();

	Goods one(int id);

}

(2)IOrderDao

package com.ljq.dao;

import com.ljq.pojo.Order;

import java.util.List;

/**
 * 订单数据库接口
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IOrderDao {

	int maxPK();

	int insert(Order order);

	List list(int userId);

}

(3)IOrderItemDao 

package com.ljq.dao;

import com.ljq.pojo.OrderItem;

import java.util.List;

/**
 * 订单项数据库接口
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IOrderItemDao {

	int maxPK();

	int insert(OrderItem item);

	List list(Integer id);

}

(4)IUserDao

package com.ljq.dao;

import com.ljq.pojo.User;

/**
 * 用户 *** 作数据接口
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IUserDao {

	User login(User user);

}
 5.数据库接口实现创建

(1)GoodsDaoImpl

package com.ljq.dao.impl;

import com.ljq.dao.IGoodsDao;
import com.ljq.pojo.Goods;
import com.ljq.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 商品 *** 作数据实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class GoodsDaoImpl implements IGoodsDao {

	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;

	@Override
	public List list() {
		List list = new ArrayList();
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select * from car_goods");
			rs = ps.executeQuery();
			while (rs.next()) {
				Goods goods = new Goods();
				goods.setId(rs.getInt(1));
				goods.setName(rs.getString(2));
				goods.setDescribe(rs.getString(3));
				goods.setPrice(rs.getInt(4));
				list.add(goods);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return list;
	}

	@Override
	public Goods one(int id) {
		List list = new ArrayList();
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select * from car_goods where id=?");
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
				Goods goods = new Goods();
				goods.setId(rs.getInt(1));
				goods.setName(rs.getString(2));
				goods.setDescribe(rs.getString(3));
				goods.setPrice(rs.getInt(4));
				return goods;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return null;
	}

}

(2)OrderDaoImpl

package com.ljq.dao.impl;

import com.ljq.dao.IOrderDao;
import com.ljq.pojo.Goods;
import com.ljq.pojo.Order;
import com.ljq.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单数据库接口实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class OrderDaoImpl implements IOrderDao {

	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;

	@Override
	public int maxPK() {
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select nvl(max(id),0)+1 from car_order");
			rs = ps.executeQuery();
			if (rs.next()) {
				return rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return 0;
	}

	@Override
	public int insert(Order order) {
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("insert into car_order values(?,?,?)");
			ps.setInt(1, order.getId());
			ps.setInt(2, order.getUserId());
			ps.setInt(3, order.getTotal());
			return ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return 0;
	}

	@Override
	public List list(int userId) {
		List list = new ArrayList<>();
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select * from car_order where user_id=?");
			ps.setInt(1, userId);
			rs = ps.executeQuery();
			while (rs.next()) {
				Order order = new Order();
				order.setId(rs.getInt(1));
				order.setUserId(rs.getInt(2));
				order.setTotal(rs.getInt(3));
				list.add(order);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return list;
	}
}

 (3)OrderItemDaoImpl

package com.ljq.dao.impl;

import com.ljq.dao.IGoodsDao;
import com.ljq.dao.IOrderItemDao;
import com.ljq.pojo.Order;
import com.ljq.pojo.OrderItem;
import com.ljq.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单项数据库接口实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class OrderItemDaoImpl implements IOrderItemDao {

	private IGoodsDao goodsDao = new GoodsDaoImpl();

	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;

	@Override
	public int maxPK() {
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select nvl(max(id),0)+1 from car_order_item");
			rs = ps.executeQuery();
			if (rs.next()) {
				return rs.getInt(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return 0;
	}

	@Override
	public int insert(OrderItem item) {
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("insert into car_order_item values(?,?,?,?,?)");
			ps.setInt(1, item.getId());
			ps.setInt(2, item.getOrderId());
			ps.setInt(3, item.getGoods().getId());
			ps.setInt(4, item.getQuantity());
			ps.setInt(5, item.getTotal());
			return ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return 0;
	}

	@Override
	public List list(Integer orderId) {
		List list = new ArrayList<>();
		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select * from car_order_item where order_id=?");
			ps.setInt(1, orderId);
			rs = ps.executeQuery();
			while (rs.next()) {
				OrderItem item = new OrderItem();
				item.setId(rs.getInt(1));
				item.setOrderId(rs.getInt(2));
				item.setGoods(goodsDao.one(rs.getInt(3)));
				item.setQuantity(rs.getInt(4));
				item.setTotal(rs.getInt(5));
				list.add(item);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return list;
	}

}

(4)UserDaoImpl

package com.ljq.dao.impl;

import com.ljq.dao.IUserDao;
import com.ljq.pojo.User;
import com.ljq.util.DBHelper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 用户 *** 作数据实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class UserDaoImpl implements IUserDao {

	private Connection con;
	private PreparedStatement ps;
	private ResultSet rs;

	@Override
	public User login(User user) {

		try {
			con = DBHelper.getCon();
			ps = con.prepareStatement("select * from car_user where account=?");
			ps.setString(1, user.getAccount());
			rs = ps.executeQuery();
			if (rs.next()) {
				User u = new User();
				u.setId(rs.getInt(1));
				u.setAccount(rs.getString(2));
				u.setPassword(rs.getString(3));
				return u;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DBHelper.close(con, ps, rs);
		}
		return null;
	}

}
 6.业务逻辑层接口

(1)IGoodsBiz.java

package com.ljq.biz;

import com.ljq.pojo.Goods;

import java.util.List;

/**
 * 商品业务逻辑层接口
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IGoodsBiz {

	List list();

	Goods one(int id);

}

(2)IOrderBiz.java

package com.ljq.biz;

import com.ljq.pojo.Order;

import java.util.List;

/**
 * 订单项业务逻辑层
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IOrderBiz {

	int maxPK();

	int insert(Order order);

	List list(int userId);

}

(3)IOrderItemBiz.java

package com.ljq.biz;

import com.ljq.pojo.OrderItem;

import java.util.List;

/**
 * 订单项业务逻辑层
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public interface IOrderItemBiz {

	int maxPK();

	int insert(OrderItem item);

	List list(Integer id);

}

 (4)IUserBiz.java

package com.ljq.biz;

import com.ljq.pojo.User;

/**
 * 用户业务逻辑层接口
 * 
 * @author 一麟
 *
 */
public interface IUserBiz {

	User login(User user);

}
7业务逻辑层接口实现类

(1)GoodsBizImpl.java

package com.ljq.biz.impl;

import com.ljq.biz.IGoodsBiz;
import com.ljq.dao.IGoodsDao;
import com.ljq.dao.impl.GoodsDaoImpl;
import com.ljq.pojo.Goods;

import java.util.List;

/**
 * 商品业务逻辑层接口实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class GoodsBizImpl implements IGoodsBiz {

	private IGoodsDao goodsDao = new GoodsDaoImpl();

	@Override
	public List list() {
		return goodsDao.list();
	}

	@Override
	public Goods one(int id) {
		return goodsDao.one(id);
	}
}

 (2)OrderBizImpl.java

package com.ljq.biz.impl;

import com.ljq.biz.IOrderBiz;
import com.ljq.dao.IOrderDao;
import com.ljq.dao.impl.OrderDaoImpl;
import com.ljq.pojo.Order;

import java.util.List;

/**
 * 订单业务逻辑层实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class OrderBizImpl implements IOrderBiz {

	private IOrderDao orderDao = new OrderDaoImpl();

	@Override
	public int maxPK() {
		return orderDao.maxPK();
	}

	@Override
	public int insert(Order order) {
		return orderDao.insert(order);
	}

	@Override
	public List list(int userId) {
		return orderDao.list(userId);
	}
}

(3)OrderItemBizImpl.java

package com.ljq.biz.impl;

import com.ljq.biz.IOrderItemBiz;
import com.ljq.dao.IOrderItemDao;
import com.ljq.dao.impl.OrderItemDaoImpl;
import com.ljq.pojo.OrderItem;

import java.util.List;

/**
 * 订单项业务逻辑层接口实现类
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class OrderItemBizImpl implements IOrderItemBiz {

	private IOrderItemDao orderItemDao = new OrderItemDaoImpl();

	@Override
	public int maxPK() {
		return orderItemDao.maxPK();
	}

	@Override
	public int insert(OrderItem item) {
		return orderItemDao.insert(item);
	}

	@Override
	public List list(Integer id) {
		return orderItemDao.list(id);
	}

}

 (4)UserBizImpl

package com.ljq.biz.impl;

import com.ljq.biz.IUserBiz;
import com.ljq.dao.IUserDao;
import com.ljq.dao.impl.UserDaoImpl;
import com.ljq.pojo.User;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 用户业务逻辑层接口实现类
 * 
 * @author 一麟
 *
 */
public class UserBizImpl implements IUserBiz {

	private IUserDao userDao = new UserDaoImpl();

	@Override
	public User login(User user) {
		User u = userDao.login(user);
		if (u == null) {
			return null;
		}
		String pwd = DigestUtils.md5Hex(user.getPassword());//md5加密
		if (!u.getPassword().equals(pwd)) {
			return null;
		}
		return u;
	}

}
 8. *** 作数据工具类

DBHepler.ja

package com.ljq.util;

import java.sql.*;

/**
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
public class DBHelper {

	// 定义链接字符串
	private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";

	// 加载驱动
	static {
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 获得链接
	public static Connection getCon() {
		try {
			return DriverManager.getConnection(URL, "scott", "sa123");
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 关闭资源
	public static void close(Connection con, PreparedStatement ps, ResultSet rs) {
		try {
			if (con != null && !con.isClosed()) {
				con.close();
			}
			if (ps != null) {
				ps.close();
			}
			if (rs != null) {
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

⭐⭐登录功能

⭐登录界面(login.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>









登录界面



	
登录
 ⭐处理登录(LoginServlet.java)

逻辑思路:表示层(servlet)-->>业务逻辑层(biz)-->>数据库访问层(dao)

代码展示

package com.ljq.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.ljq.biz.IUserBiz;
import com.ljq.biz.impl.UserBizImpl;
import com.ljq.pojo.OrderItem;
import com.ljq.pojo.User;

/**
 * 登录验证
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebServlet("/login.do")//设置路径
public class LoginServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		// 获取登录数据
		String account = req.getParameter("account");
		String password = req.getParameter("password");
		User user = new User(0,account,password);
		// 通过业务逻辑层进行登录验证
		
		User u = new UserBizImpl().login(user);

		//如果没有登录就跳转到登录界面
		if (u == null) {
			resp.sendRedirect("login.jsp");
		} else {
			// 将数据存入session中
			req.getSession().setAttribute("user", u);
			// 生成一个购物车	
			List car = new ArrayList<>();
			req.getSession().setAttribute("car", car);
			// 将总价存入session中
			req.getSession().setAttribute("total", 0);
			// 跳转至首页
			resp.sendRedirect("index.do");
		}
	}

}

 效果图

 ⭐⭐过滤器(LoginFilter.java)

实现原理:先过滤所有项目的所有文件,再指定文件不经过过滤器。

package com.ljq.filter;

import java.io.IOException;

import javax.servlet.*;

import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 过滤层
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebFilter("/*") // 指的是这个类适用于整个项目的所有文件,即过滤所有请求
public class LoginFilter implements Filter {

	/*
	 * 逻辑处理: 如果登录成功了,就正常通行,反之就跳转到登录界面
	 */

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		// 设置登录界面放行
		HttpServletRequest hsrq = (HttpServletRequest) request;
		HttpServletResponse hsrp = (HttpServletResponse) response;
		// 获取登录页面的路径
		String path = hsrq.getServletPath();
		System.out.println("dgsh.hjhi".substring("dgsh.hjhi".length() - 3));
		if ("/login.jsp".equals(path) || "/login.do".equals(path)
				|| "js".equals(path.substring(path.lastIndexOf(".") + 1))
				|| "css".equals(path.substring(path.lastIndexOf(".") + 1))) {// 当文件路径为login.jsp或者login.do、".js"、".css"就不执行过滤 *** 作
			chain.doFilter(hsrq, hsrp);
			return;
		}
		Object user = hsrq.getSession().getAttribute("user");
		if (user == null) {
			hsrp.sendRedirect("login.jsp");
			return;
		} else {
			chain.doFilter(request, response);
		}

	}

}

 

 ⭐⭐主页商品显示:

逻辑思路:查询数据(dao&biz)-->读取数据(servlet)->显示数据(jsp)

效果图:

主页(index.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>












    


	
		${user.account},welcome tomain
	
	
		点我去购物车🛒
	
	
				
商品编号 商品名称 商品描述 商品价格 商品 *** 作
${goods.id} ${goods.name} ${goods.describe} ${goods.price} Join In ShoppingCar
<%--思路逻辑:login.jsp(表单拿值)-->>login.do(登录验证)-->>index.do(拿到主页需要的数据)-->>index.jsp(显示数据)--%>

⭐主页数据显示(index.do) -->indexservlet

package com.ljq.servlet;

import com.ljq.biz.IGoodsBiz;
import com.ljq.biz.impl.GoodsBizImpl;
import com.ljq.pojo.Goods;

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 java.io.IOException;
import java.util.List;

/**
 * 主页数据处理
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebServlet("/index.do")
public class IndexServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List list = new GoodsBizImpl().list();
		req.setAttribute("list", list);
		req.getRequestDispatcher("index.jsp").forward(req, resp);
	}

}
⭐加入购物车(addServlet)
package com.ljq.servlet;

import com.ljq.biz.IGoodsBiz;
import com.ljq.biz.impl.GoodsBizImpl;
import com.ljq.pojo.Goods;
import com.ljq.pojo.OrderItem;

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 java.io.IOException;
import java.util.List;

/**
 * 增加购物车处理
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebServlet("/add.do")
public class AddServlet extends HttpServlet {

	private IGoodsBiz GoodsBiz = new GoodsBizImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List car = (List) req.getSession().getAttribute("car");
		int id = Integer.parseInt(req.getParameter("id"));
		boolean f = true;
		for (OrderItem item : car) {
			if (item.getGoods().getId().equals(id)) {
				item.setQuantity(item.getQuantity() + 1);
				item.setTotal(item.getQuantity() * item.getGoods().getPrice());
				f = false;
				break;
			}
		}
		if (f) {
			OrderItem item = new OrderItem();
			Goods one = GoodsBiz.one(id);
			item.setGoods(one);
			item.setQuantity(1);
			item.setTotal(one.getPrice());
			car.add(item);
		}
		req.getSession().setAttribute("total", car.stream().mapToInt(OrderItem::getTotal).sum());
		resp.sendRedirect("index.do");
	}

}

购物车效果图:

 

 

⭐⭐删除购物车(deleteServlet)
package com.ljq.servlet;

import com.ljq.pojo.Goods;
import com.ljq.pojo.OrderItem;

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 java.io.IOException;
import java.util.List;

/**
 * 删除 *** 作处理
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebServlet("/delete.do")
public class DeleteServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//通过session获取购物车(注意拿到的是object类型所以需要强转为list类型)
		List car = (List) req.getSession().getAttribute("car");
		int id = Integer.parseInt(req.getParameter("id"));
		OrderItem i = null;
		for (OrderItem item : car) {
			if (item.getGoods().getId().equals(id)) {
				i = item;
				break;
			}
		}
		car.remove(i);
		req.getSession().setAttribute("total", car.stream().mapToInt(OrderItem::getTotal).sum());
		resp.sendRedirect("car.jsp");
	}

}
⭐⭐清空购物车(ClearServlet)
package com.ljq.servlet;

import com.ljq.pojo.OrderItem;

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 java.io.IOException;
import java.util.List;

/**
 * 清空购物车处理
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebServlet("/clear.do")
public class ClearServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List car = (List) req.getSession().getAttribute("car");
		car.clear();
		resp.sendRedirect("car.jsp");
	}

}
⭐⭐结算(calcservlet)
package com.ljq.servlet;

import java.io.IOException;
import java.util.List;

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.ljq.biz.IOrderBiz;
import com.ljq.biz.IOrderItemBiz;
import com.ljq.biz.impl.OrderBizImpl;
import com.ljq.biz.impl.OrderItemBizImpl;
import com.ljq.pojo.Order;
import com.ljq.pojo.OrderItem;
import com.ljq.pojo.User;

/**
 * 结算清算功能的处理
 * 
 * @author 一麟
 *
 */
@SuppressWarnings("all")
@WebServlet("/calc.do")
public class CalcServlet extends HttpServlet {

	private IOrderBiz orderBiz = new OrderBizImpl();
	private IOrderItemBiz orderItemBiz = new OrderItemBizImpl();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 购物车在哪里?
		List car = (List) req.getSession().getAttribute("car");
		// 获得用户
		User user = (User) req.getSession().getAttribute("user");
		// 什么是结算? 将数据放到【订单】【订单项】
		if (car.isEmpty()) {
			// 返回购物车
			resp.sendRedirect("car.jsp");
			return;
		}
		// 计算总和
		int sum = 0;
		for (OrderItem item : car) {
			sum += item.getTotal();
		}
		// 优先结算订单
		Order order = new Order();
		order.setId(orderBiz.maxPK());
		order.setUserId(user.getId());
		order.setTotal(sum);
		// 将订单放到数据库
		int i = orderBiz.insert(order);
		if (i > 0) {
			// 如果订单插入成功了,则插入订单项
			for (OrderItem item : car) {
				// item没有id
				item.setId(orderItemBiz.maxPK());
				// 也没有订单编号
				item.setOrderId(order.getId());                   
				orderItemBiz.insert(item);
			}
			// 结算完毕
			car.clear();
			// 清空价格
			req.getSession().setAttribute("total", 0);
		}

		// 返回购物车
		resp.sendRedirect("car.jsp");
	}

}

好啦,这期的分享就到这了下完完善MVC购物车小项目。o( ̄▽ ̄)

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/757837.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-01
下一篇 2022-05-01

发表评论

登录后才能评论

评论列表(0条)

保存