我是靠谱客的博主 过时纸飞机,最近开发中收集的这篇文章主要介绍JavaWeb之Servlet项目02前言:知识回顾:一,项目介绍二,代码详解 总结:,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

目录

前言:

知识回顾:

一,项目介绍

1.购物车界面

2.订单界面

3.订单详情界面

二,代码详解

com.zking.biz包

IGoodsBiz.java:

IUserBiz.java:

IOrderBiz.java:

IOrderItemBiz.java :

com.zking.biz.impl包

GoodsBizImpl.java:

UserBizImpl.java:

OrderBizImpl.java:

OrderItemBizImpl.java:

com.zking.dao包

IGoodsDao.java:

IUserDao.java:

com.zking.dao.impl包

GoodsDaoImpl.java:

UserDaoImpl.java:

OrderDaoImpl.java:

OrderItemDaoImpl.java:

com.zking.filter包

LoginFilter.java:

com.zking.pojo包

Goods.java:

OrderItem.java:

User.java:

Order.java:

com.zking.servlet包

AddServlet.java:

ClearServlet.java:

DelServlet.java:

IndexServlet.java:

LoginServlet.java:

UpdServlet.java:

CalcServlet.java:

OrderServlet.java:

ItemServlet.java:

com.zking.util包

DBHelper:

Web部分:

car.jsp:

index.jsp:

login.jsp:

item.jsp:

order.jsp:

 总结:


前言:

上次给大家介绍到了项目的前半部分,今天接着来给大家介绍项目的一些其他功能。

知识回顾:

JavaWeb之Servlet项目01icon-default.png?t=M3K6https://blog.csdn.net/weixin_65474399/article/details/124466836?spm=1001.2014.3001.5502


一,项目介绍

上次给大家介绍了登录界面与主界面以及购物车界面,今天接着来给大家介绍一下购物车的其他功能。

1.购物车界面

点击继续购买的按钮可以回到主界面继续往购物车增加商品,点击订单结算按钮可以清空购物车,同时在生成一个订单,及相应的订单项,点击查看订单按钮可以跳转订单界面,点击清空按钮可以清空购物车。

2.订单界面

点击继续购买按钮可以回到主界面,点击返回购物车界面可以返回购物车。

3.订单详情界面

这个界面与订单界面相呼应,一个订单里面可以有很多的小订单项,这个界面就是用来专门查看订单项。

二,代码详解

com.zking.biz包

IGoodsBiz.java:

package com.zking.biz;

import com.zking.pojo.Goods;

import java.util.List;


public interface IGoodsBiz {

    List<Goods> list();

    Goods one(int id);

}

IUserBiz.java:

package com.zking.biz;

import com.zking.pojo.User;

public interface IUserBiz {

    User login(User user);

}

IOrderBiz.java:

package com.zking.biz;

import com.zking.pojo.Order;

import java.util.List;


public interface IOrderBiz {

    int maxPK();

    int insert(Order order);

    List<Order> list(int userId);

}

IOrderItemBiz.java :

package com.zking.biz;

import com.zking.pojo.OrderItem;

import java.util.List;


public interface IOrderItemBiz {

    int maxPK();

    int insert(OrderItem item);

    List<OrderItem> list(Integer id);

}

com.zking.biz.impl包

GoodsBizImpl.java:

package com.zking.biz.impl;

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

import java.util.List;


public class GoodsBizImpl implements IGoodsBiz {

    private IGoodsDao goodsDao=new GoodsDaoImpl();

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

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

UserBizImpl.java:

package com.zking.biz.impl;

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


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());
        if(!u.getPassword().equals(pwd)){
            return null;
        }
        return u;
    }

}

OrderBizImpl.java:

package com.zking.biz.impl;

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

import java.util.List;


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<Order> list(int userId) {
        return orderDao.list(userId);
    }
}

OrderItemBizImpl.java:

package com.zking.biz.impl;

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

import java.util.List;


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<OrderItem> list(Integer id) {
        return orderItemDao.list(id);
    }

}

com.zking.dao包

IGoodsDao.java:

package com.zking.dao;

import com.zking.pojo.Goods;

import java.util.List;


public interface IGoodsDao {

    List<Goods> list();

    Goods one(int id);

}

IUserDao.java:

package com.zking.dao;

import com.zking.pojo.User;


public interface IUserDao {

    User login(User user);

}

IOrderDao.java:

package com.zking.dao;

import com.zking.pojo.Order;

import java.util.List;


public interface IOrderDao {

    int maxPK();

    int insert(Order order);

    List<Order> list(int userId);

}

IOrderItemDao.java:

package com.zking.dao;

import com.zking.pojo.OrderItem;

import java.util.List;


public interface IOrderItemDao {

    int maxPK();

    int insert(OrderItem item);

    List<OrderItem> list(Integer id);

}

com.zking.dao.impl包

GoodsDaoImpl.java:

package com.zking.dao.impl;

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

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


public class GoodsDaoImpl implements IGoodsDao {

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

    @Override
    public List<Goods> list() {
        List<Goods> list = new ArrayList<Goods>();
        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<Goods> list = new ArrayList<Goods>();
        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;
    }

}

UserDaoImpl.java:

package com.zking.dao.impl;

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

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


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;
    }

}

OrderDaoImpl.java:

package com.zking.dao.impl;

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

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


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<Order> list(int userId) {
        List<Order> 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;
    }
}

OrderItemDaoImpl.java:

ackage com.zking.dao.impl;

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

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


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<OrderItem> list(Integer orderId) {
        List<OrderItem> 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;
    }

}

com.zking.filter包

LoginFilter.java:

package com.zking.dao.impl;

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

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


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;
    }

}

com.zking.pojo包

Goods.java:

package com.zking.pojo;

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


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;
	}
     

}

OrderItem.java:

package com.zking.pojo;

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


public class OrderItem {

    private Integer id;
    private Integer orderId;
    private Goods goods;
    private Integer quantity;
    private Integer total;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getOrderId() {
		return orderId;
	}
	public void setOrderId(Integer orderId) {
		this.orderId = orderId;
	}
	public Goods getGoods() {
		return goods;
	}
	public void setGoods(Goods goods) {
		this.goods = goods;
	}
	public Integer getQuantity() {
		return quantity;
	}
	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}
	public Integer getTotal() {
		return total;
	}
	public void setTotal(Integer total) {
		this.total = total;
	}
	public OrderItem() {
		// TODO Auto-generated constructor stub
	}
	public OrderItem(Integer id, Integer orderId, Goods goods, Integer quantity, Integer total) {
		super();
		this.id = id;
		this.orderId = orderId;
		this.goods = goods;
		this.quantity = quantity;
		this.total = total;
	}
}

User.java:

package com.zking.pojo;

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


public class User {

    private Integer id;
    private String account;
    private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getAccount() {
		return account;
	}
	public void setAccount(String account) {
		this.account = account;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
    
    public User() {
		// TODO Auto-generated constructor stub
	}
	public User(Integer id, String account, String password) {
		super();
		this.id = id;
		this.account = account;
		this.password = password;
	}
    
}

Order.java:

package com.zking.pojo;

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

public class Order {

    private Integer id;
    private Integer userId;
    private Integer total;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public Integer getUserId() {
		return userId;
	}
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	public Integer getTotal() {
		return total;
	}
	public void setTotal(Integer total) {
		this.total = total;
	}
    
    public Order() {
		// TODO Auto-generated constructor stub
	}
	public Order(Integer id, Integer userId, Integer total) {
		super();
		this.id = id;
		this.userId = userId;
		this.total = total;
	}
    

}

com.zking.servlet包

AddServlet.java:

package com.zking.servlet;

import com.zking.biz.IGoodsBiz;
import com.zking.biz.impl.GoodsBizImpl;
import com.zking.pojo.Goods;
import com.zking.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;


@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<OrderItem> car = (List<OrderItem>) 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");
    }

}

ClearServlet.java:

package com.zking.servlet;

import com.zking.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;


@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<OrderItem> car = (List<OrderItem>)req.getSession().getAttribute("car");
        car.clear();
        resp.sendRedirect("car.jsp");
    }

}

DelServlet.java:

package com.zking.servlet;

import com.zking.pojo.Goods;
import com.zking.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;


@WebServlet("/del.do")
public class DelServlet 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<OrderItem> car = (List<OrderItem>)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");
    }

}

IndexServlet.java:

package com.zking.servlet;

import com.zking.biz.IGoodsBiz;
import com.zking.biz.impl.GoodsBizImpl;
import com.zking.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;


@WebServlet("/index.do")
public class IndexServlet 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<Goods> list = goodsBiz.list();
        req.setAttribute("list",list);
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }

}

LoginServlet.java:

package com.zking.servlet;

import com.zking.biz.IUserBiz;
import com.zking.biz.impl.UserBizImpl;
import com.zking.pojo.Goods;
import com.zking.pojo.OrderItem;
import com.zking.pojo.User;

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


@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {

    private IUserBiz userBiz=new UserBizImpl();


    @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();
        user.setAccount(account);
        user.setPassword(password);
        User u = userBiz.login(user);
        if(u==null){
            resp.sendRedirect("login.jsp");
        }else{
            req.getSession().setAttribute("user",u);
            List<OrderItem> car=new ArrayList<>();
            req.getSession().setAttribute("car",car);
            req.getSession().setAttribute("total",0);
            resp.sendRedirect("index.do");
        }
    }

}

UpdServlet.java:

package com.zking.servlet;

import com.zking.pojo.Goods;
import com.zking.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;

@WebServlet("/upd.do")
public class UpdServlet 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<OrderItem> car = (List<OrderItem>)req.getSession().getAttribute("car");
        int id = Integer.parseInt(req.getParameter("id"));
        int type = Integer.parseInt(req.getParameter("type"));
        for (OrderItem item : car) {
            if(item.getGoods().getId().equals(id)){
                int count = item.getQuantity() + type;
                if(count<1)count=1;
                if(count>5)count=5;
                item.setQuantity(count);
              item.setTotal(item.getQuantity()*item.getGoods().getPrice());
                req.getSession().setAttribute("total",car.stream()
                        .mapToInt(OrderItem::getTotal)
                        .sum());
                break;
            }
        }
        resp.sendRedirect("car.jsp");
    }

}

CalcServlet.java:

package com.zking.servlet;

import com.zking.biz.IOrderBiz;
import com.zking.biz.IOrderItemBiz;
import com.zking.biz.impl.OrderBizImpl;
import com.zking.biz.impl.OrderItemBizImpl;
import com.zking.pojo.Order;
import com.zking.pojo.OrderItem;
import com.zking.pojo.User;
import org.apache.commons.codec.binary.StringUtils;

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;

@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<OrderItem> car = (List<OrderItem>)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");
    }

}

OrderServlet.java:

package com.zking.servlet;

import com.zking.biz.IOrderBiz;
import com.zking.biz.IOrderItemBiz;
import com.zking.biz.impl.OrderBizImpl;
import com.zking.biz.impl.OrderItemBizImpl;
import com.zking.pojo.Order;
import com.zking.pojo.OrderItem;
import com.zking.pojo.User;

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;


@WebServlet("/order.do")
public class OrderServlet extends HttpServlet {

    private IOrderBiz orderBiz=new OrderBizImpl();

    @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 {
        //获得用户
        User user = (User)req.getSession().getAttribute("user");
        List<Order> list = orderBiz.list(user.getId());
        //放到请求作用域中
        req.setAttribute("list",list);
        //返回order.jsp
        req.getRequestDispatcher("order.jsp").forward(req,resp);
    }

}

ItemServlet.java:

package com.zking.servlet;

import com.zking.biz.IOrderBiz;
import com.zking.biz.IOrderItemBiz;
import com.zking.biz.impl.OrderBizImpl;
import com.zking.biz.impl.OrderItemBizImpl;
import com.zking.pojo.Order;
import com.zking.pojo.OrderItem;
import com.zking.pojo.User;

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;


@WebServlet("/item.do")
public class ItemServlet extends HttpServlet {

    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 {
        //接受订单的id
        Integer id = Integer.parseInt(req.getParameter("id"));
        //根据订单id查询对应的订单项
        List<OrderItem> list = orderItemBiz.list(id);
        //放到请求作用域中
        req.setAttribute("list",list);
        //返回order.jsp
        req.getRequestDispatcher("item.jsp").forward(req,resp);
    }

}

com.zking.util包

DBHelper:

package com.zking.util;

import java.sql.*;


@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", "tiger");
        } 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();
        }
    }

}

Web部分:

car.jsp:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ 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="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/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.account},您好, <small>这是购物车</small>
    </h1>
    <h1>
        <a href="index.do" class="btn btn-default">继续购买</a>
        <a href="" class="btn btn-default">订单结算</a>
        <a href="" class="btn btn-default">查看订单</a>
        <a href="clear.do" class="btn btn-default">清空????</a>
    </h1>
    <table class="table table-bordered table-striped">
        <tbody>
        <tr>
            <th>商品编号</th>
            <th>商品名字</th>
            <th>商品数量</th>
            <th>商品总价</th>
            <th>商品操作</th>
        </tr>
        <c:forEach items="${car}" var="item">
            <tr>
                <td>${item.goods.id}</td>
                <td>${item.goods.name}</td>
                <td>${item.quantity}</td>
                <td>${item.total}</td>
                <td>
                    <a href="del.do?id=${item.goods.id}" class="btn btn-default">删除</a>
                    <a href="upd.do?id=${item.goods.id}&type=1" class="btn btn-default">+1</a>
                    <a href="upd.do?id=${item.goods.id}&type=-1" class="btn btn-default">-1</a>
                </td>
            </tr>
        </c:forEach>
        </tbody>
    </table>
    <h1>
        total: ${total}
    </h1>
</div>
</body>
</html>

index.jsp:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ 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="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>主界面</title>
    <style>
        body {
            padding: 20px 40px;
        }
    </style>
</head>
<c:if test="${list == null}">
    <c:redirect url="index.do"/>
</c:if>
<body>
<h1>
    ${user.account},您好, <small>这是首页</small>
</h1>
<h1>
    <a href="car.jsp" class="btn btn-primary" onclick="">点我去购物车????</a>
</h1>
<table class="table table-bordered table-striped">
    <tbody>
    <tr>
        <th>商品编号</th>
        <th>商品名称</th>
        <th>商品描述</th>
        <th>商品价格</th>
        <th>商品操作</th>
    </tr>
    <c:forEach items="${list}" var="goods">
    <tr>
        <td>${goods.id}</td>
        <td>${goods.name}</td>
        <td>${goods.describe}</td>
        <td>${goods.price}</td>
        <td>
            <a href="add.do?id=${goods.id}" class="btn btn-default">加入????</a>
        </td>
    </tr>
    </c:forEach>
    </tbody>
</table>
<%--
    login.jsp-(表单)->login.do-(登录验证)->index.do-(拿到首页需要的数据)->index.jsp 显示数据
--%>
</body>
</html>

login.jsp:


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

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/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 class="container">
<form action="login.do" method="post">
    <h1>登录</h1>
    <div class="form-group">
        <input name="account" class="form-control" placeholder="用户名">
    </div>
    <div class="form-group">
        <input name="password" class="form-control" placeholder="密码">
    </div>
    <div class="form-group">
        <button class="btn btn-primary btn-block">登录</button>
    </div>
</form>
</body>
</html>

item.jsp:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${list == null}">
    <c:redirect url="item.do"/>
</c:if>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/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>
        您好, <small>这是订单项界面</small>
    </h1>
    <h1>
        <a href="index.jsp" class="btn btn-default">继续购买</a>
        <a href="car.jsp" class="btn btn-default">返回购物车</a>
    </h1>
    <table class="table table-bordered table-striped">
        <tbody>
        <tr>
            <th>订单项编号</th>
            <th>订单项商品名称</th>
            <th>订单项商品单价</th>
            <th>订单项下单数量</th>
            <th>订单项下单总价</th>
        </tr>
        <c:forEach items="${list}" var="item">
        <tr>
            <td>${item.id}</td>
            <td>${item.goods.name}</td>
            <td>${item.goods.price}</td>
            <td>${item.quantity}</td>
            <td>${item.total}</td>
        </tr>
        </c:forEach>
        </tbody>
    </table>

</div>

</body>
</html>

order.jsp:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:if test="${list == null}">
    <c:redirect url="order.do"/>
</c:if>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
    <script src="${pageContext.request.contextPath}/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>
        您好, <small>这是订单界面</small>
    </h1>
    <h1>
        <a href="index.jsp" class="btn btn-default">继续购买</a>
        <a href="car.jsp" class="btn btn-default">返回购物车</a>
    </h1>
    <table class="table table-bordered table-striped">
        <tbody>
        <tr>
            <th>订单编号</th>
            <th>订单总价</th>
            <th>订单操作</th>
        </tr>
        <c:forEach items="${list}" var="order">
        <tr>
            <td>${order.id}</td>
            <td>${order.total}</td>
            <td>
                <a href="item.do?id=${order.id}" class="btn btn-default">查看详情</a>
            </td>
        </tr>
        </c:forEach>
        </tbody>
    </table>

</div>

</body>
</html>

 总结:

今天的分享就到此为止啦,购物车项目已经完结,下期精彩继续哦。

最后

以上就是过时纸飞机为你收集整理的JavaWeb之Servlet项目02前言:知识回顾:一,项目介绍二,代码详解 总结:的全部内容,希望文章能够帮你解决JavaWeb之Servlet项目02前言:知识回顾:一,项目介绍二,代码详解 总结:所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(41)

评论列表共有 0 条评论

立即
投稿
返回
顶部