图书商城 --- 代码回溯2

2019-12-10  本文已影响0人  幽泉流霜

前端显示界面

左侧书籍列表

因为我们的所有分类都是要从后台添加的分类所拿到,所以同理要先进入到相应的servlet,然后转发请求,图书显示也同理

<body>
<%@include file="top.jsp" %>
<div class="container">
    <div class="col-md-3">
        <jsp:include page="/category"></jsp:include>
    </div>
    <div class="col-md-9">
        <jsp:include page="/bookshow"></jsp:include>
    </div>
</div>

</body>

这里要注意因为使用的是动态引入,而且引入的是servlet链接,所以后面的请求转发应写include而不是forword

  
@WebServlet(name = "catagoryshow",urlPatterns = "/category")
public class catagoryshow extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        CategoryService cs = new CategoryServiceImpl();
        List<Category> lc = cs.ShowAllCategory();
        req.setAttribute("category",lc);
        req.getRequestDispatcher("/FontMain/categoryleft.jsp").include(req,resp);
    }
}
<div class="">
    <c:forEach items="${requestScope.books}" var="book">
        <div class="bookitem panel panel-primary">
            <div class="panel-heading">书名:${book.name}</div>
            <div class="panel-body">
                <div class="col-sm-6">
                    <img class="img-responsive" src="../BookImage/${book.image_id}">
                </div>
                <div class="col-sm-6">
                    <ul class="list-group">
                        <li class="list-group-item">书名:${book.name}</li>
                        <li class="list-group-item">作者:${book.author}</li>
                        <li class="list-group-item">描述:${book.description}</li>
                        <li class="list-group-item">价格${book.price}</li>
                    </ul>
                </div>
            </div>
            <input class="btn btn-primary " type="button" onclick="InsertCart(this);" value="加入购物车">
            <p class="hidden">${book.id}</p>
        </div>
    </c:forEach>
</div>

效果


image.png

用户登录注册

前端页面

   <div class="login">
        <form action="/registerlogin">
            <input type="hidden" name="oper" value = "login">
            <div class="form-group">
                <label>账号</label>
                <input type="text" class="form-control" placeholder="" value = ""name = "luname">
            </div>
            <div class="form-group">
                <label>密码</label>
                <input type="password" class="form-control" placeholder="" value="" name="lpwd">
            </div>

            <button type="submit" class="btn btn-primary">登录</button>
            <span  class="glyphicon glyphicon-remove exit"></span>
            <c:if test="${!empty(requestScope.message2)}">
                <p class="result2">用户名或密码错误</p>
            </c:if>

        </form>
    </div>
    <div class="register">
        <form id = "registerpanel" action="/registerlogin">
            <input type="hidden" name="oper" value = "register">
            <div class="form-group">
                <label>账号</label>
                <input type="text" class="form-control" value = ""id = "zhanghao" name = "uname"placeholder="">
            </div>
            <div class="form-group">
                <label>密码</label>
                <input type="password" class="form-control" value = ""id = "pwd"placeholder="">
            </div>
            <div class="form-group">
                <label>确认密码</label>
                <input type="password" class="form-control" id = "checkpwd" value = ""name = "pwd"placeholder="">
            </div>
            <div class="form-group">
                <label for="exampleInputEmail1">邮箱地址</label>
                <input type="email" class="form-control" id="exampleInputEmail1" name = "email" value = ""placeholder="Email">
            </div>
            <button type="submit" class="btn btn-primary">注册</button>
            <span  class="glyphicon glyphicon-remove exit"></span>
            <c:if test="${!empty(requestScope.message)}">
                <p class="result">已注册成功</p>
            </c:if>
        </form>
    </div>


    <span class="cover"></span>

-js

  if(document.getElementById("myname")){
        document.getElementById("loginbutton").style.display = "none";
        document.getElementById("registerbutton").style.display = "none";

    }
    function Toactive(obj) {
        obj.classList.add("active");
        console.log(obj);
    }
    document.getElementById("loginbutton").onclick = function () {
        var mini_login = document.getElementsByClassName("login")[0];
        var cover = document.getElementsByClassName("cover")[0];
        mini_login.style.display = "block";
        cover.style.display = "block";
    }
    document.getElementById("registerbutton").onclick = function () {
        var mini_register = document.getElementsByClassName("register")[0];
        var cover = document.getElementsByClassName("cover")[0];
        mini_register.style.display = "block";
        cover.style.display = "block";
    }
   document.getElementsByClassName("exit")[0].onclick = function () {
        var mini_login = document.getElementsByClassName("login")[0];
        var cover = document.getElementsByClassName("cover")[0];
        mini_login.style.display = "none";
        cover.style.display = "none";
    }
    document.getElementsByClassName("exit")[1].onclick = function () {
        var mini_register = document.getElementsByClassName("register")[0];
        var cover = document.getElementsByClassName("cover")[0];
        mini_register.style.display = "none";
        cover.style.display = "none";
    }

完成效果图


denglx.gif

登录servlet

同样 我们将其封装成了函数

  private void Login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("登录函数运行");
        String luname = req.getParameter("luname");
        String lpwd = req.getParameter("lpwd");
        if(luname.equals("admin")&&lpwd.equals("admin")){
            req.getRequestDispatcher("/BackMain/AddCategory.jsp").forward(req,resp);
        }
        User u = new User();
        u.setUname(luname);
        u.setPwd(lpwd);
        System.out.println(u);
        User nu = us.CheckUser(u);
        if(nu !=null){
            HttpSession hs=req.getSession();
            hs.setAttribute("user",nu);
            resp.sendRedirect("/FontMain/Index.jsp");
        }else{
            req.setAttribute("message2",0);
            req.getRequestDispatcher("/FontMain/Index.jsp").forward(req,resp);
        }
    }

如果登录成功就将用户信息 存储到session中,并在前台隐藏掉登录和删除,然后显示用户名

 <c:if test="${!empty(sessionScope.user)}">
                    <span>欢迎     </span>
                    <span id="myname">${sessionScope.user.uname}</span>
                    <a href="/registerlogin?oper=exit">退出</a>
                </c:if>

否则就传一个message到前台表示登录不成功

 <c:if test="${!empty(requestScope.message2)}">
                <p class="result2">用户名或密码错误</p>
            </c:if>

购物车设计

为了防止购物车单项重复 并且 方便删除项目
我们新建一个购物车item表示购物车单项

cartitem

public class CartItem {
    private Book book;
    private int number;
    private float price;

//各种get set
}

cart

public class Cart {
    private Map<Integer,CartItem> mc = new HashMap<>();
    //书籍id 和 购物项
    private float allprice;

    public void AddBook(Book book){
        CartItem cartItem = mc.get(book.id);
        if(cartItem ==null){
            cartItem = new CartItem();
            cartItem.setBook(book);
            cartItem.setNumber(1);
            mc.put(book.id,cartItem);
        }else{
            int currentnum =  cartItem.getNumber();
            cartItem.setNumber(++currentnum);
        }
    }

    public void DeleteItem(int bookid){
     mc.remove(bookid);
    }

    public Map<Integer, CartItem> getMc() {
        return mc;
    }

    public void setMc(Map<Integer, CartItem> mc) {
        this.mc = mc;
    }

    public float getPrice(){
          allprice = 0;
        for(int i:mc.keySet()){
           CartItem ci = mc.get(i);
           allprice += ci.getPrice();
        }
        return allprice;
    }

}

加入购物车操作

当我们在前台单击加入购物车的时候,我们用ajax将数据传入到bussiness servlet

   <input class="btn btn-primary " type="button" onclick="InsertCart(this);" value="加入购物车">

<script>
    function InsertCart(obj) {
        alert("已加入购物车");
        var bookid = obj.nextElementSibling.innerHTML;

        var ajax;
        if (window.XMLHttpRequest) {
            ajax = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            ajax = new ActiveXObject("Msxml2.XMLHTTP");
        }
        //复写onreadystatechange函数
        ajax.onreadystatechange = function () {
            if (ajax.readyState == 4) {
            }
            if (ajax.status == 404) {
            }
        }
        ajax.open("get", "/business?oper=addItem&bookid="+bookid);
        ajax.send(null);
    }
</script>

bussiness servlet

加入购物车前 我们需要判断用户是否登录
如果没有登录 就在前台传回一个message

   HttpSession hs = req.getSession();
        User user  = (User)hs.getAttribute("user");
        if(user ==null){
            req.setAttribute("message","请先登录后购买");
            req.getRequestDispatcher("/FontMain/Mycart.jsp").forward(req,resp);
        }

加入操作

 private void AddItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession hs = req.getSession();
        Cart ct = (Cart)hs.getAttribute("cart");
        if( ct== null){
            ct = new Cart();
        }

        int bookid =  Integer.parseInt(req.getParameter("bookid"));
        BookService bs = new BookServiceImpl();
        Book book = bs.FindBook(bookid);
        ct.AddBook(book);

        hs.setAttribute("cart",ct);
    }

为了方便这里我们就不建数据库了 ,直接将购物车的内容放发到了session中,缺点是如果退出登录购物车里的内容就会消失,优点是:可以少写一个dao层
所以用户务必在退出的时候生成订单 ,某种情况下可以促进消费

购物车显示


        <c:forEach items="${sessionScope.cart.mc}" var="cartitem">
            <div class="container">
                <div class="col-sm-2">
                    <img class="img-responsive" src="../BookImage/${cartitem.value.book.image_id}">
                </div>
                <div class="col-sm-3">
                    <ul class="list-group">
                        <li class="list-group-item list-group-item-info">书名:${cartitem.value.book.name}</li>
                        <li class="list-group-item list-group-item-info">作者:${cartitem.value.book.author}</li>
                        <li class="list-group-item list-group-item-info">数量:${cartitem.value.number}</li>
                        <li class="list-group-item list-group-item-info">价钱:${cartitem.value.price}</li>
                    </ul>
                </div>
                <div class="col-sm-2">
                    <span class="glyphicon glyphicon-remove deleteitem" onclick="DeleteItem(this);"></span>
                    <div class="hidden">${cartitem.value.book.id}</div>
                </div>
            </div>
        </c:forEach>

删除操作

这里我们类比后台删除图书,同样用ajax完成

 private void DeleteItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession hs = req.getSession();
        Cart ct = (Cart)hs.getAttribute("cart");

        int itemid = Integer.parseInt(req.getParameter("itemid"));

        ct.DeleteItem(itemid);
        hs.setAttribute("cart",ct);
        resp.getWriter().write("总价:"+String.valueOf(ct.getPrice()));
    }

gouwuche.gif

订单

OrderItem

public class CartItem {
    private Book book;
    private int number;
    private float price;

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public float getPrice() {
        return number*book.getPrice();
    }

    public void setPrice(float price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "CartItem{" +
                "book=" + book +
                ", number=" + number +
                ", price=" + price +
                '}';
    }

    public CartItem() {
    }

    public CartItem(Book book, int number, float price) {
        this.book = book;
        this.number = number;
        this.price = price;
    }
}

表示购物车每一项

Order

public class Order {
    int id;
    private Date date;
    private float price;
    private boolean state;
    private int user_id;
    private Set<OrderItem> so = new HashSet<>();
//设置一个 Set
}

生成订单

private void AddOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession hs = req.getSession();
        //拿到用户id
        int user_id = Integer.parseInt(req.getParameter("user_id"));
        //从session中拿到购物车的数据
        Cart ct = (Cart)hs.getAttribute("cart");
        //拿到购物车中具体map数据
        Map<Integer, CartItem> cartitems = ct.getMc();
       //设置Set order
        Set<OrderItem> so = new HashSet<>();
//        Order order = new Order(0,new Date(),ct.getPrice(),false,user_id);
        Order order = new Order();
        order.setId(0);
        for(int i:cartitems.keySet()){
            CartItem ci = cartitems.get(i);
            OrderItem ot = new OrderItem(0,ci.getBook().getId(),order.getId(),ci.getNumber(),ci.getPrice());
            so.add(ot);
        }
        order.setSo(so);
        order.setDate(new Date());
        order.setPrice(ct.getPrice());
        order.setState(false);
        order.setUser_id(user_id);

        //将order放入od
        od.AddOrder(order);
        List<Order> lo = od.FindUserOrder(user_id);
        hs.setAttribute("orders", lo);
        resp.sendRedirect("/FontMain/MyOrder.jsp");
    }
上一篇下一篇

猜你喜欢

热点阅读