JavaWeb 购物车项目(一)

  • 阿里云国际版折扣https://www.yundadi.com

  • 阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

    今天的学习主要是完成一个购物车项目该项目中使用servlet完成对于不知道servlet不知道如何使用的去看servlet的使用该篇文章该文章中有教大家如何使用servlet。

    目录

    一.项目所需表

     二.购物车项目实操

     1.登录操作

    2.首页操作

    购物车数据操作 CarServlet, 我们在点击首页的加入购物车页面时会到该类中进行数据操作将商品添加进购物车

    3.购物车

    三.过滤器


    一.项目所需表

     我们一共需要使用到四张表格将代码数据提供给到大家大家直接拿到数据库中运行四张表格分别是用户表商品表订单表订单详情表。

    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
    );
    
    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, '拉稀弹筒', ',就亿点点', 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;

    如图所示

    • 订单表中显示的数据肯定是登录进来的用户他的所有订单数据一个用户对应着多个订单。
    •  订单详情表对应着订单的编号商品的编号我们是根据自己想查看的订单的详细  数据一个订单对应着多件商品。

     二.购物车项目实操

         该购物车我们具备登录首页将商品加入购物车购物车界面在实操的时候首先我们需要把需要的包导进去。

     

      文件放置位置

     

     1.登录操作

           思路:

    • 登录界面具备的方法就是去到数据库查询用户是否存在如果用户存在我们就跳转到首页去

         pojo包下的用户实体类代码如下 User

    package com.yjx.pojo;
    /**
     * 用户实体类
     * @author zjjt
     *
     */
    public class User {
    	 
    	private Integer id;
    	private String name;
    	private String pwd;
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getPwd() {
    		return pwd;
    	}
    	public void setPwd(String pwd) {
    		this.pwd = pwd;
    	}
    	
    	
    	public User() {
    		// TODO Auto-generated constructor stub
    	}
    	
    	public User(Integer id, String name, String pwd) {
    		super();
    		this.id = id;
    		this.name = name;
    		this.pwd = pwd;
    	}
    	
    	
    	@Override
    	public String toString() {
    		return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + "]";
    	}
    	
    	
    	
    
    }
    

         用户数据库访问层接口代码如下: IUserDao

    package com.yjx.dao;
    /**
     * 用户数据访问层接口
     * @author zjjt
     *
     */
    
    import com.yjx.pojo.User;
    
    public interface   IUserDao {
        
    	//登录验证
    	User login(User u);
    }
    

       用户数据库访问层代码如下:  该类中具备登录验证的方法 UserDaoImpl

    package com.yjx.dao.impl;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    
    import com.yjx.dao.IUserDao;
    import com.yjx.pojo.User;
    import com.yjx.util.DBHeper;
    
    public class UserDaoImpl implements IUserDao {
    	
    	private Connection con;
    	private PreparedStatement ps;
    	private ResultSet   rs;
          /**
           * 登录验证方法
           */
    	@Override
    	public User login(User u) {
    		try {
    			con=DBHeper.getCon();
    			ps=con.prepareStatement("select * from car_user where account=?");
    			ps.setString(1, u.getName());
    			rs=ps.executeQuery();
    			if(rs.next()) {
    				User user=new User();
    				user.setId(rs.getInt(1));
    				user.setName(rs.getString(2));
    				user.setPwd(rs.getString(3));
    				return user;
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}    
    }
    

      用户业务逻辑层接口代码如下IUserBiz

    package com.yjx.biz;
    
    import com.yjx.pojo.User;
    
    public interface IUserBiz {
         
    	//登录验证方法
    	 User login(User u);
    }
    

      用户业务逻辑层代码如下UserBizImpl

    package com.yjx.biz.impl;
    
    import org.apache.commons.codec.digest.DigestUtils;
    
    import com.yjx.biz.IUserBiz;
    import com.yjx.dao.IUserDao;
    import com.yjx.dao.impl.UserDaoImpl;
    import com.yjx.pojo.User;
    
    public class UserBizImpl implements IUserBiz {
      
    	 IUserDao userdao=new UserDaoImpl();
    	
    	/**
    	 * 登录验证方法
    	 */
    	  @Override
    	public User login(User u) {
    		User user=userdao.login(u);
    		String pwd=DigestUtils.md5Hex(u.getPwd());
    		if(user.getPwd().equals(pwd)) {
    			return user;
    		}
    		return null;
    		
    	}
    }

     登录页面代码login.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    
    <!DOCTYPE html>
    <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="bootstrap-3.3.7-dist\js\bootstrap.js"></script>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    
    <title>登录界面</title>
    <style>
    form {
    	width: 500px;
    	margin:auto;
    }
    </style>
    </head>
    <body>
    	<form action="login.do" method="post">
    		<h1>登录</h1>
    		<div class="form-group">
    			<input name="uname" class="form-control" placeholder="用户名">
    		</div>
    		<div class="form-group">
    			<input name="upwd" class="form-control" placeholder="密码">
    		</div>
    		<div class="form-group">
    			<button class="btn btn-primary btn-block">登录</button>
    		</div>
    	</form>
    
    </body></html>

      实现登录功能代码如下 : LoginServlet 

      在这里我们将用户存进session中当用户一进来我们就给用户一个购物车该购物车中存放我们在首页加入购物车的商品然后在购物车界面遍历。

    package com.yjx.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.yjx.biz.IGoodsBiz;
    import com.yjx.biz.IUserBiz;
    import com.yjx.biz.impl.GoodsBizImpl;
    import com.yjx.biz.impl.UserBizImpl;
    import com.yjx.pojo.Car;
    import com.yjx.pojo.User;
    /**
     * 实现登录功能
     * @author zjjt
     *
     */
    @WebServlet("/login.do")
    public class LoginServlet extends HttpServlet{
    	
    	IUserBiz userbiz=new UserBizImpl();
    	
    	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 {
    		
    		req.setCharacterEncoding("utf-8");
    		String name=req.getParameter("uname");
    		String pwd=req.getParameter("upwd");
    		
    		User u=new User(0,name,pwd);
    	    userbiz.login(u);
    	    if(u!=null) {
    	    	//将用户存入session中
    	    	req.getSession().setAttribute("user", u);
    	    	//进来的时候就给该用户一个购物车,将该购物车存在session中
    	    	List<Car> car=new ArrayList<Car>();
    	    	req.getSession().setAttribute("car",car);
    	    	//总价
    	    	req.getSession().setAttribute("sum", 0);
    	    	//跳转到实现首页功能
    	    	resp.sendRedirect("index.do");
    	}else {
    		    resp.sendRedirect("login.jsp");
    	}
    
    	}
    }
    

    2.首页操作

      思路:

    • 首页界面需要显示商品表中的数据
    • 点击加入购物车将数据加入进购物车

       商品表的pojo包下的商品实体类代码如下:Goods

    package com.yjx.pojo;
    /**
     * 商品实体类
     * @author zjjt
     *
     */
    public class Goods {
     
    	private Integer id;
    	private String name;
    	private String describe;
    	private Integer price;
    	
    	
    	public Integer getId() {
    		return id;
    	}
    	public void setId(Integer id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getDescribe() {
    		return describe;
    	}
    	public void setDescribe(String describe) {
    		this.describe = describe;
    	}
    	public Integer getPrice() {
    		return price;
    	}
    	public void setPrice(Integer price) {
    		this.price = price;
    	}
    	
    	public Goods() {
    		// TODO Auto-generated constructor stub
    	}
    	
    	
    	public Goods(Integer id, String name, String describe, Integer price) {
    		super();
    		this.id = id;
    		this.name = name;
    		this.describe = describe;
    		this.price = price;
    	}
    	
    	
    	
    	
    	@Override
    	public String toString() {
    		return "Goods [id=" + id + ", name=" + name + ", describe=" + describe + ", price=" + price + "]";
    	}
    	
    	
    	
    	
    }
    

      商品数据访问层接口 IGoodsDao

    package com.yjx.dao;
    
    import java.util.List;
    
    import com.yjx.pojo.Goods;
    /**
     * 商品数据访问层的接口
     * @author zjjt
     *
     */
    public interface IGoodsDao {
    	
    	//查询商品表中的所有数据
    	List<Goods> selectAll();
    	
    	//根据id查询
    	Goods selestId(int id);
    	
    	
    
    }
    

    商品数据访问代码如下 GoodsDaoImpl

    package com.yjx.dao.impl;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;
    
    import com.yjx.dao.IGoodsDao;
    import com.yjx.pojo.Goods;
    import com.yjx.util.DBHeper;
    /**
     * 商品数据访问层
     * @author zjjt
     *
     */
    public class GoodsDaoImpl implements IGoodsDao{
    	private Connection con;
    	private PreparedStatement ps;
    	private ResultSet rs;
        
    	/**
    	 * 查询商品表中的所有数据
    	 */
    	  @Override
    	public List<Goods> selectAll() {
    		List<Goods> list=new ArrayList<Goods>();
    		try {
    			con=DBHeper.getCon();
    			ps=con.prepareStatement("select * from car_goods");
    			rs=ps.executeQuery();
    			while(rs.next()) {
    			Goods g=new Goods();
    			g.setId(rs.getInt(1));
    			g.setName(rs.getString(2));
    			g.setDescribe(rs.getString(3));
    			g.setPrice(rs.getInt(4));
    			list.add(g);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally {
    			DBHeper.getColes(con, ps, rs);
    		}
    		return list;
    	}
    	 
    	  /**
    	   * 根据商品id进行查询
    	   */
    	  @Override
    	public Goods selestId(int id) {
    		  try {
    				con=DBHeper.getCon();
    				ps=con.prepareStatement("select * from car_goods where id=?");
    				ps.setInt(1, id);
    				rs=ps.executeQuery();
    				if(rs.next()) {
    				Goods g=new Goods();
    				g.setId(rs.getInt(1));
    				g.setName(rs.getString(2));
    				g.setDescribe(rs.getString(3));
    				g.setPrice(rs.getInt(4));
    				return g;
    				}
    			} catch (Exception e) {
    				e.printStackTrace();
    			}finally {
    				DBHeper.getColes(con, ps, rs);
    			}
    		   return null;
    	}
    }
    

    商品数据业务逻辑层接口代码如下:IGoodsBiz

    package com.yjx.biz;
    
    import java.util.List;
    
    import com.yjx.pojo.Goods;
    /**
     * 商品业务逻辑层接口
     * @author zjjt
     *
     */
    public interface IGoodsBiz {
    
    	//查询商品表中的所有数据
    	List<Goods> selectAll();
    	
    	//根据id查询
         Goods selestId(int id);
    
    }
    

    商品数据业务逻辑层代码如下: GoodsBizImpl  

    package com.yjx.biz.impl;
    
    import java.util.List;
    
    import com.yjx.biz.IGoodsBiz;
    import com.yjx.dao.IGoodsDao;
    import com.yjx.dao.impl.GoodsDaoImpl;
    import com.yjx.pojo.Goods;
    /**
     * 商品业务逻辑层
     * @author zjjt
     *
     */
    public class GoodsBizImpl implements IGoodsBiz{
    	
    	IGoodsDao dao=new GoodsDaoImpl();
      
    	/**
    	 * 查询商品表中所有数据
    	 */
    	   @Override
    	public List<Goods> selectAll() {
    		
    		return dao.selectAll();
    	}
    	   
    	   /**
    	    * 根据id查询
    	    */
    	   @Override
    	public Goods selestId(int id) {
    		
    		return dao.selestId(id);
    	}
    }
    

    商品数据操作代码如下:    所以登录成功后先跳转到这里在将商品数据从全查出来然后存进session中在首页的时候在遍历 IndexServlet

    package com.yjx.servlet;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.yjx.biz.IGoodsBiz;
    import com.yjx.biz.impl.GoodsBizImpl;
    import com.yjx.pojo.Goods;
    /**
     * 首页商品数据显示
     * @author zjjt
     *
     */
    @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 {
    		
    		IGoodsBiz goodsbiz=new  GoodsBizImpl();
    	    List<Goods> list=goodsbiz.selectAll();
    	    
    	    //将该集合中的数据存进request中
    	    req.setAttribute("goods", list);
    	    //使用request存放需要转发
    	    req.getRequestDispatcher("index.jsp").forward(req, resp);
    	    		
    	}
    
    }
    

    首页界面代码如下index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    
    <!-- 商品首页 -->
    
    <!DOCTYPE html>
    <html>
    <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="bootstrap-3.3.7-dist\js\bootstrap.js"></script>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <style>
    body {
    	padding: 20px 40px;
    }
    </style>
    </head>
    <body>
    	<h1>
    		${user.name}<small>这是首页</small>
    	</h1>
    	<h1>
    		<a class="btn btn-primary" href="car.jsp">点我去购物车</a>
    	</h1>
    	<table class="table table-bordered table-striped">
    		<tbody><tr>
    			<th>商品编号</th>
    			<th>商品名称</th>
    			<th>商品价格</th>
    			<th>商品操作</th>
    		</tr>
    		<!-- 遍历 -->
       <c:forEach items="${goods}" var="g">
     		<tr>
    			<td>${g.id}</td>
    			<td>${g.name}</td>
    			<td>${g.price}</td>
    			<td><a href="car.do?id=${g.id}" class="btn btn-default">加入</a></td>
    		</tr>
    		
      </c:forEach>
    
    </body></html>

    购物车数据操作 CarServlet, 我们在点击首页的加入购物车页面时会到该类中进行数据操作将商品添加进购物车

    package com.yjx.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.yjx.biz.IGoodsBiz;
    import com.yjx.biz.impl.GoodsBizImpl;
    import com.yjx.pojo.Car;
    import com.yjx.pojo.Goods;
    
    /**
     * 购物车数据
     * @author zjjt
     *
     */
    @WebServlet("/car.do")
    public class CarServlet extends HttpServlet{
    	
    	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> car=(List<Car>)req.getSession().getAttribute("car");
    	//先将传过来的id接收到
    	int id=Integer.parseInt(req.getParameter("id"));
    	boolean f=true;
    	
    	//判断该商品是否已经存在购物车中如何存在只在数量上相加
    	 for (Car c : car) {
    		if(c.getGoods().getId()==id) {
    			//设置数量加1
    		   c.setCount(c.getCount()+1);
    		   //设置商品总价
    		   c.setTotal(c.getCount()*c.getGoods().getPrice());
    		   f=false;
    		   break;
    		}
    	}
    	
    	 if(f) {
    	//当商品不存在相同的进入这里
    	//根据id进行查询商品
    	Goods goods=goodsbiz.selestId(id);
    	Car c=new Car();
    	c.setGoods(goods);
    	//商品的数量设置
    	c.setCount(1);
    	//商品的总价设置
    	c.setTotal(c.getGoods().getPrice());
        car.add(c);
    	}
    	
    	 //遍历购物车将总价加上
    	 int sum=0;
    	 for (Car car2 : car) {
    		sum+=car2.getTotal();
    	}
    	 req.getSession().setAttribute("sum",sum);
    	 
    	 resp.sendRedirect("index.do");
    	}
         
    	
    }

    3.购物车

     购物车中具备查看我们加入购物和的商品然后对商品的数量增加减当商品存在购物车中了我们在首页将同一件商品在加入购物车时只有数量加1。

     购物车的pojo包下的实体类代码如下:Car

    package com.yjx.pojo;
    /**
     * 购物车实体类
     * @author zjjt
     *
     */
    public class Car {
    	
    	private Goods  goods;
    	private Integer count;
    	private Integer total;
    	
    	
    	public Goods getGoods() {
    		return goods;
    	}
    	public void setGoods(Goods goods) {
    		this.goods = goods;
    	}
    	public Integer getCount() {
    		return count;
    	}
    	public void setCount(Integer count) {
    		this.count = count;
    	}
    	public Integer getTotal() {
    		return total;
    	}
    	public void setTotal(Integer total) {
    		this.total = total;
    	}
    	
    	
    	public Car() {
    		// TODO Auto-generated constructor stub
    	}
    	
    	public Car(Goods goods, Integer count, Integer total) {
    		super();
    		this.goods = goods;
    		this.count = count;
    		this.total = total;
    	}
    	
    	
    	
    	
    	
    
    }
    

    购物车页面代码如下: car.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
    <!DOCTYPE html>
    <html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="bootstrap-3.3.7-dist\js\bootstrap.js"></script>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>我的购物车</title>
    </head>
    <body>
    <div class="container">
    	<h1>
    		${user.name}<small>这是购物车</small>
    	</h1>
    	<h1>
    		<button onclick="location.href=&#39;index.do&#39;" class="btn btn-default">继续购买</button>
    		<button onclick="location.href=&#39;calc.do&#39;" class="btn btn-default">订单结算</button>
    		<button onclick="location.href=&#39;myOrder.do&#39;" class="btn btn-default">查看订单</button>
    	</h1>
    	<table class="table table-bordered table-striped">
    		<tr>
    			<td>商品编号</td>
    			<td>商品名字</td>
    			<td>商品单价</td>
    			<td>商品数量</td>
    			<td>商品总价</td>
    			<td>商品操作</td>
    		</tr>
    		<c:forEach items="${car}" var="c">
    		<tr>
    			<td>${c.goods.id}</td>
    			<td>${c.goods.name}</td>
    			<td>${c.goods.price}</td>
    			<td><a href="updCar.do?id=${c.goods.id}&type=1" class="btn btn-default">+</a>   ${c.count}   <a href="updCar.do?id=${c.goods.id}&type=-1" class="btn btn-default">-</a></td>
    			<td>${c.total}</td>
    			<td><a href="delCar.do?id=${c.goods.id}" class="btn btn-default">商品删除</a></td>
    			
    		</tr>
    		</c:forEach>
          </table>
    	</div>
    	
    	<h1>总价:${sum}</h1>
    
    </body></html>

    点击加号或者减号数据操作代码如下updCarServlet

    当点击加号或者减号携带过来一个数判断是加法还是减法进行对数量上的加减

    package com.yjx.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.yjx.biz.IGoodsBiz;
    import com.yjx.biz.impl.GoodsBizImpl;
    import com.yjx.pojo.Car;
    import com.yjx.pojo.Goods;
    
    /**
     * 修改商品数量操作
     * @author zjjt
     *
     *
     */
    
    @WebServlet("/updCar.do")
    public class updCarServlet 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> car=(List<Car>)req.getSession().getAttribute("car");
    		//接收到传过来的值
    		int id=Integer.parseInt(req.getParameter("id"));
    		int type=Integer.parseInt(req.getParameter("type"));
    		
    		for (Car c : car) {
    			 if(c.getGoods().getId().equals(id)) {
    				 int count=c.getCount()+type;
    				//设置该商品的数量
    				 if(count<1)break;
    				 
    	            c.setCount(count);
    	            c.setTotal(c.getCount()*c.getGoods().getPrice());
    			 }
    		}
    		
    		 //遍历购物车将总价加上
    		 int sum=0;
    		 for (Car car2 : car) {
    			sum+=car2.getTotal();
    		}
    		 req.getSession().setAttribute("sum",sum);
    		
    		 resp.sendRedirect("car.jsp");
    	}
    	
    
    }
    

    购物车数据删除代码如下 delCarServlet

    package com.yjx.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.yjx.pojo.Car;
    
    /**
     * 删除商品操作
     * @author zjjt
     *
     */
    @WebServlet("/delCar.do")
    public class delCarServlet 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> car=(List<Car>)req.getSession().getAttribute("car");
    		//先接收到id
    	   int id=Integer.parseInt(req.getParameter("id"));
    	    Car i=null;
    	   //遍历购物车
    	   for (Car c : car) {
    		 if(c.getGoods().getId().equals(id)){
    			 i=c;
    		 }
    	}
    	   //将商品删除
    	   car.remove(i);
    	   
    	   //遍历购物车将总价加上
    		 int sum=0;
    		 for (Car car2 : car) {
    			sum+=car2.getTotal();
    		}
    		 req.getSession().setAttribute("sum",sum);
    	   
    	   resp.sendRedirect("car.jsp");
    	}
    	
    	
    
    }
    

    三.过滤器

    过滤器的作用就是当我们没有登录时有一些界面无法进入所以我们进在过滤器中进行过滤满足我们条件的我们就放行不满足条件的就让他继续在登录页面。

    package com.yjx.filter;
    
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.yjx.pojo.User;
    
    /**
     * 过滤
     * @author zjjt
     *
     */
    public class LoginFilter implements Filter{
    	//过滤的作用因为当我们没有登录成功时只有允许在登录界面不允许跳转到别的界面所以我们选择使用过滤不满足我们进入的
    	//        需求就让他跳回登录界面。
    	
    	
          //1.先实现filter接口
    	  //2.先实例一个集合将我们需要放行的页面放入
    	  List<String> list=new ArrayList();
    	  
    	  {
    		  list.add("/login.jsp");
    		  list.add("/login.do");
    		  list.add(".css");
    		  list.add(".js");
    	  }
    	  
    	  
    	@Override
    public void doFilter(ServletRequest req, ServletResponse reps, FilterChain chain)throws IOException, ServletException {
    	  //将请求和响应强转成它的子类
    	  HttpServletRequest request=(HttpServletRequest)req;
    	  HttpServletResponse response=(HttpServletResponse)reps;
    	  
    	  //获取到路径
    	 String path=request.getServletPath();
    	 boolean f=false;
    	 //遍历集合和获取到的路径进行判断
    	 for(String p:list) {
    		 if(path.endsWith(p)){//判断是否是以增加进集合的的数据结尾的
    			 //如果以该为结尾的话
    			 f=true;
    			 System.out.print(f);
    			 break;
    		 }
    	 }
    	  
    	
    	 if(f){
    		 //如果存在list集合中就放行
    		 chain.doFilter(request, response);//放行语句
    		  return;
    	 }
    	 
    	 //判断用户是否已经登录啦如果session中存在user那么就放行
    	      User u=(User)request.getAttribute("user");//得到一个用户进行判断
    	      if(u!=null) {
    	    	  chain.doFilter(request, response);
    	      }else {
    	    	  //用户没有登录就返回登录界面
    	    	  response.sendRedirect("login.jsp");
    	      }
    		
    	}
    	
    }
    

    今天的学习就到这里啦。

  • 阿里云国际版折扣https://www.yundadi.com

  • 阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
    标签: Java