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

目录

一.项目所需表

二.购物车项目实操

1.登录操作

2.首页操作

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

3.购物车

三.过滤器


一.项目所需表

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

create table car_user(id number primary key,accountvarchar2(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,pricenumbernot 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(idnumber 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,totalnumber 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_uservalues (1, '2890@fox.com', 'ff9830c42660c1dd1942844f8069b74a');-- root123insert into car_uservalues (2, '2357@fox.com', 'e10adc3949ba59abbe56e057f20f883e');-- 123456insert into car_goodsselect 1, '丝袜奶茶', '冰冰娘娘,很好喝', 99from dualunionselect 2, '勃勃奶茶', '啊~,好冰冰', 29from dualunionselect 3, '蜜雪大补丁', '可以加个桃桃', 59from dualunionselect 4, '臭咖啡', '人气最高', 88from dualunionselect 5, '雪王咖啡', 'incredible taste', 999from dualunionselect 6, '拉稀弹筒', ',就亿点点', 1from dual;insert into car_order_itemvalues (1, 1, 1, 2, 99 * 2);insert into car_order_itemvalues (2, 1, 2, 3, 29 * 3);insert into car_order_itemvalues (3, 1, 6, 100, 100);insert into car_ordervalues (1, 1, 99 * 2 + 29 * 3 + 100);insert into car_order_itemvalues (4, 2, 3, 2, 59 * 2);insert into car_order_itemvalues (5, 2, 4, 3, 88 * 3);insert into car_order_itemvalues (6, 2, 5, 100, 999 * 100);insert into car_ordervalues (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;}@Overridepublic 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;/** * 登录验证方法 */@Overridepublic User login(User u) {try {con=DBHeper.getCon();ps=con.prepareStatement("select * from car_user where account=" />

用户业务逻辑层接口代码如下: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();/** * 登录验证方法 */@Overridepublic 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

登录界面form {width: 500px;margin:auto;}

登录

实现登录功能代码如下 : 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();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req,resp);}@Overrideprotected 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=new ArrayList();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;}@Overridepublic 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 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;/** * 查询商品表中的所有数据 */@Overridepublic List selectAll() {List list=new ArrayList();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进行查询 */@Overridepublic 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 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();/** * 查询商品表中所有数据 */ @Overridepublic List selectAll() {return dao.selectAll();}/*** 根据id查询*/ @Overridepublic 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{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {IGoodsBiz goodsbiz=newGoodsBizImpl();List list=goodsbiz.selectAll();//将该集合中的数据存进request中req.setAttribute("goods", list);//使用request存放,需要转发req.getRequestDispatcher("index.jsp").forward(req, resp);}}

首页界面代码如下:index.jsp

body {padding: 20px 40px;}

${user.name}这是首页

点我去购物车

购物车数据操作 :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();@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {List car=(List)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 Goodsgoods;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

我的购物车

${user.name}这是购物车

商品编号商品名称商品价格商品操作
${g.id}${g.name}${g.price}加入
商品编号商品名字商品单价商品数量商品总价商品操作
${c.goods.id}${c.goods.name}${c.goods.price}+ ${c.count} -${c.total}商品删除

总价:${sum}

点击加号或者减号数据操作代码如下: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{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//拿到购物车List car=(List)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{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//拿到购物车List car=(List)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 list=new ArrayList();{list.add("/login.jsp");list.add("/login.do");list.add(".css");list.add(".js");}@Overridepublic 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");}}}

今天的学习就到这里啦。