网上书城之购物车功能,门户书籍搜索

网上书城之购物车功能,门户书籍搜索

实现功能

今天要实现的功能就和标题一样 门户书籍搜索功能和购物车功能 今天也是直接上代码

代码块

因为有些代码在同一个包里面 所以我就直接上包 不分开了(有点麻烦哈哈哈哈)
Book

package com.huangjie.entity;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.huangjie.utils.PinYinUtil;


public class Book {
    private long id;
    private String name;
    private String pinyin;
    private long cid;
    private String author;
    private float price;
    private  String image="暂无图片";
    private String publishing;
    private String description;
    private int state;
    @JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
    private Date deployTime;
    private int sales;

    public void setName(String name) {
        this.name = name;
        this.pinyin= PinYinUtil.getAllPingYin(name);
    }

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getPinyin() {
		return pinyin;
	}

	public void setPinyin(String pinyin) {
		this.pinyin = pinyin;
	}

	public long getCid() {
		return cid;
	}

	public void setCid(long cid) {
		this.cid = cid;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public float getPrice() {
		return price;
	}

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

	public String getImage() {
		return image;
	}

	public void setImage(String image) {
		this.image = image;
	}

	public String getPublishing() {
		return publishing;
	}

	public void setPublishing(String publishing) {
		this.publishing = publishing;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public Date getDeployTime() {
		return deployTime;
	}

	public void setDeployTime(Date deployTime) {
		this.deployTime = deployTime;
	}

	public int getSales() {
		return sales;
	}

	public void setSales(int sales) {
		this.sales = sales;
	}

	public String getName() {
		return name;
	}

	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + ", pinyin=" + pinyin + ", cid=" + cid + ", author=" + author
				+ ", price=" + price + ", image=" + image + ", publishing=" + publishing + ", description="
				+ description + ", state=" + state + ", deployTime=" + deployTime + ", sales=" + sales + "]";
	}

	public Book(long id, String name, String pinyin, long cid, String author, float price, String image,
			String publishing, String description, int state, Date deployTime, int sales) {
		super();
		this.id = id;
		this.name = name;
		this.pinyin = pinyin;
		this.cid = cid;
		this.author = author;
		this.price = price;
		this.image = image;
		this.publishing = publishing;
		this.description = description;
		this.state = state;
		this.deployTime = deployTime;
		this.sales = sales;
	}

	public Book() {
		super();
	}
    
    
}

BookDao

package com.huangjie.Dao;



import java.util.List;

import com.huangjie.entity.Book;
import com.huangjie.utils.BaseDao;
import com.huangjie.utils.PageBean;
import com.huangjie.utils.StringUtils;



public class BookDao extends BaseDao<Book> {
    public List<Book> newsBook(Book book, PageBean pageBean) throws Exception {
        String sql = "select * from t_easyui_book where state = 2 order by deployTime desc";
        return super.executeQuery(sql, pageBean, Book.class);
    }

    public List<Book> hotBook(Book book, PageBean pageBean) throws Exception {
        String sql = "select * from t_easyui_book where state = 2 order by sales desc";
        return super.executeQuery(sql, pageBean, Book.class);
    }
    //书籍搜索
    public List<Book> list(Book book, PageBean pageBean) throws Exception {
        String name = book.getName();
        long cid = book.getCid();
        int state = book.getState();
        String sql = "select * from t_easyui_book where true ";

        if (StringUtils.isNotBlank(name)) {
            sql += " and name like '%" + name + "%'";
        }
        if(cid != 0){
            sql += " and cid = " + cid;
        }
        return super.executeQuery(sql, pageBean, Book.class);
    }
    }

BookAction

package com.huangjie.web;



import java.io.File;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.huangjie.Dao.BookDao;
import com.huangjie.entity.Book;
import com.huangjie.framework.ActionSupport;
import com.huangjie.framework.ModelDriven;
import com.huangjie.utils.DateUtil;
import com.huangjie.utils.EasyuiResult;
import com.huangjie.utils.PageBean;
import com.huangjie.utils.PropertiesUtil;
import com.huangjie.utils.ResponseUtil;


public class BookAction extends ActionSupport implements ModelDriven<Book> {
    private Book book = new Book();
    private BookDao bookDao = new BookDao();
//书籍搜索
    public String findByName(HttpServletRequest request, HttpServletResponse response) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        try {
            List<Book> list = this.bookDao.list(book, pageBean);
            request.setAttribute("books", list);
            request.setAttribute("pageBean", pageBean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "findBook";
    }
public String news(HttpServletRequest request, HttpServletResponse response) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        try {
            List<Book> list = this.bookDao.newsBook(book, pageBean);
            ResponseUtil.writeJson(response, EasyuiResult.ok(pageBean.getTotal(), list));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

   
    public String hot(HttpServletRequest request, HttpServletResponse response) {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        try {
            List<Book> list = this.bookDao.hotBook(book, pageBean);
            ResponseUtil.writeJson(response, EasyuiResult.ok(pageBean.getTotal(), list));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    @Override
    public Book getModel() {
        return book;
    }
}

findBook.jsp

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

<head>
<meta charset="utf-8">
<title>书籍搜索页</title>
<!-- 写全局样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/default/easyui.css">   
<!-- 定义图标的样式 -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/themes/icon.css">   
<!--组件库源文件的js文件-->
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.min.js"></script>  
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>   
<script type="text/javascript" src="${pageContext.request.contextPath}/static/js/index.js"></script>

    <title>网上书城首页</title>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/4.4.1/css/bootstrap.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/css/fg.css" rel="stylesheet">
    <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>
    <script src="${pageContext.request.contextPath}/static/js/index.js"></script>
</head>
<body class="text-center">
<div class="container">
    <div class="row head">
        <div class="col-md-12">
            <i>
                您好,欢迎来到网上书城!
            </i>
            <b>
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/login.jsp">登录</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/register.jsp">注册</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/shopping.action?methodName=list">我的购物车</a> |
                <a type="button" class="text-primary" href="${pageContext.request.contextPath}/">网站首页</a>
            </b>
        </div>
    </div>
    <!-- 横幅搜索栏 start -->
    <div class="row banner">
        <div class="img1"></div>
        <div class="col-md-12">
            <form class="form" action="${pageContext.request.contextPath}/book.action?methodName=findByName" method="post">
                <%--<input type="hidden" name="methodName" value="findByName">--%>
                <input type="text" name="name" value="" id="input" class="search">
                <input type="submit" class="btn btn-primary" value="查询">
            </form>
        </div>
    </div>
    <!-- 横幅搜索栏 end -->
    <!-- 页面主体内容 start -->
    <div class="row content">
        <div class="col-md-3 float-left c-left">
            <ul class="list-group">
                <li class="list-group-item">书籍分类</li>
            </ul>
        </div>
        <%--${books}--%>
        <div class="col-md-9 float-right c-right">
            <c:forEach var="b" items="${books}">
                <div class="media">
                    <img style="width: 100px;height: 140px;" src="${pageContext.request.contextPath}${b.image}" class="align-self-center mr-3" alt="...">
                    <div class="media-body text-left">
                        <p>${b.name}</p>
                        <p>作者:${b.author}</p>
                        <p>价格:${b.price}</p>
                        <p>出版社:${b.publishing}</p>
                        <p>书籍简介:${b.description}</p>
                        <span>
								<a type="button" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=add&name=${b.name}&price=${b.price}&num=1&total=${b.price}">加入购物车</a>
								<a type="button" class="btn btn-danger" href="${pageContext.request.contextPath}/shopping.action?methodName=pay">去结算</a>
							</span>
                    </div>
                </div>
                <hr>
            </c:forEach>

            <%--<div class="media">--%>
            <%--<img src="imgs/2.png" class="align-self-center mr-3" alt="...">--%>
            <%--<div class="media-body text-left">--%>
            <%--<p>第一商会</p>--%>
            <%--<p>作者:寒川子</p>--%>
            <%--<p>价格:¥24.80</p>--%>
            <%--<p>出版社:北京联合出版公司</p>--%>
            <%--<p>书籍简介:超级畅销书作家寒川子创作历时三年全新力作!讲述财富与权力“离不开,靠不住”的明暗法则</p>--%>
            <%--<span>--%>
            <%--<button type="button" class="btn btn-danger">加入购物车</button>--%>
            <%--<button type="button" class="btn btn-danger">去结算</button>--%>
            <%--</span>--%>
            <%--</div>--%>
            <%--</div>--%>
            <%--<hr>--%>

            <h:page pageBean="${pageBean}"></h:page>
        </div>
    </div>
    <!-- 页面主体内容 end -->
    <!-- 网站版权 start -->
    <div class="row footer">
        <div class="col-md-12">
            Copyright ©2020 MM教育,版权所有
        </div>
    </div>
    <!-- 网站版权 end -->
</div>
<script type="text/javascript">
    function searchByType(cid){
        location.href='${pageContext.request.contextPath}/book.action?methodName=findByType&cid='+cid;
    };
</script>

</body>
</html>

ShopGoodsVo

package com.huangjie.vo;


import java.util.Objects;


public class ShopGoodsVo {
    private String name;
    private float price;
    private int num;
    private float total;

    private String consignee;
    private String phone;
    private String postalcode;
    private String address;
    private int sendType;

    private String pageStr;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ShopGoodsVo that = (ShopGoodsVo) o;
        return Float.compare(that.price, price) == 0 &&
                num == that.num &&
                Float.compare(that.total, total) == 0 &&
                Objects.equals(name, that.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, price, num, total);
    }

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public float getPrice() {
		return price;
	}

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

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	public float getTotal() {
		return total;
	}

	public void setTotal(float total) {
		this.total = total;
	}

	public String getConsignee() {
		return consignee;
	}

	public void setConsignee(String consignee) {
		this.consignee = consignee;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getPostalcode() {
		return postalcode;
	}

	public void setPostalcode(String postalcode) {
		this.postalcode = postalcode;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getSendType() {
		return sendType;
	}

	public void setSendType(int sendType) {
		this.sendType = sendType;
	}

	public String getPageStr() {
		return pageStr;
	}

	public void setPageStr(String pageStr) {
		this.pageStr = pageStr;
	}

	@Override
	public String toString() {
		return "ShopGoodsVo [name=" + name + ", price=" + price + ", num=" + num + ", total=" + total + ", consignee="
				+ consignee + ", phone=" + phone + ", postalcode=" + postalcode + ", address=" + address + ", sendType="
				+ sendType + ", pageStr=" + pageStr + "]";
	}

	public ShopGoodsVo(String name, float price, int num, float total, String consignee, String phone,
			String postalcode, String address, int sendType, String pageStr) {
		super();
		this.name = name;
		this.price = price;
		this.num = num;
		this.total = total;
		this.consignee = consignee;
		this.phone = phone;
		this.postalcode = postalcode;
		this.address = address;
		this.sendType = sendType;
		this.pageStr = pageStr;
	}

	public ShopGoodsVo() {
		super();
	}
    
    
}

ShoppingAction

package com.huangjie.web;

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

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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huangjie.Dao.OrderDao;
import com.huangjie.Dao.OrderItemDao;
import com.huangjie.entity.Order;
import com.huangjie.entity.OrderItem;
import com.huangjie.entity.User;
import com.huangjie.framework.ActionSupport;
import com.huangjie.framework.ModelDriven;
import com.huangjie.utils.EasyuiResult;
import com.huangjie.utils.ResponseUtil;
import com.huangjie.utils.StringUtils;
import com.huangjie.vo.ShopGoodsVo;


public class ShoppingAction extends ActionSupport implements ModelDriven<ShopGoodsVo> {
    private ShopGoodsVo shopGoodsVo = new ShopGoodsVo();
    private OrderDao orderDao = new OrderDao();
    private OrderItemDao orderItemDao = new OrderItemDao();


    public String createOrder(HttpServletRequest request, HttpServletResponse response) {
        try {
            User currentUser = (User) request.getSession().getAttribute("currentUser");
            long uid = currentUser.getId();
            
            String pageStr = shopGoodsVo.getPageStr();
            float total = 0;
            List<OrderItem> orderItems = new ArrayList<>();
            OrderItem orderItem = null;

            for (String s : pageStr.substring(1).split(",")) {
                orderItem = new OrderItem();
                String[] items = s.split("-");
                orderItem.setBid(items[0]);
                orderItem.setQuantity(Integer.valueOf(items[2]));
                total += Float.valueOf(items[items.length-1]);
                orderItems.add(orderItem);
            }
//            System.out.println(shopGoodsVo);
            Order order = new Order();
            order.setAddress(shopGoodsVo.getAddress());
            order.setConsignee(shopGoodsVo.getConsignee());
            order.setOrderPrice(total);
            order.setOrderState(1);
            order.setPhone(shopGoodsVo.getPhone());
            order.setPostalcode(shopGoodsVo.getPostalcode());
            order.setSendType(shopGoodsVo.getSendType());
            order.setUid(uid);
            int res = this.orderDao.add(order);


            Order newest = this.orderDao.newest();

            for (OrderItem item : orderItems) {
                item.setOid(newest.getId());
                this.orderItemDao.add(item);
            }


            ResponseUtil.writeJson(response, res);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String del(HttpServletRequest request, HttpServletResponse response) {
        ObjectMapper om = new ObjectMapper();
        try {
            User currentUser = (User) request.getSession().getAttribute("currentUser");
            long uid = currentUser.getId();
            String shopId = "shopId_" + uid;
            String shopVoStr = (String) request.getServletContext().getAttribute(shopId);
            List<ShopGoodsVo> shopGoodsVos = om.readValue(shopVoStr, List.class);
            int index = Integer.valueOf(shopGoodsVo.getPageStr());
            shopGoodsVos.remove(index);
            request.getServletContext().setAttribute(shopId,om.writeValueAsString(shopGoodsVos));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list(request,response);
    }

    public String clear(HttpServletRequest request, HttpServletResponse response) {
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        long uid = currentUser.getId();
        String shopId = "shopId_" + uid;
        request.getServletContext().removeAttribute(shopId);
        try {
            ResponseUtil.writeJson(response, EasyuiResult.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String list(HttpServletRequest request, HttpServletResponse response) {
        ObjectMapper om = new ObjectMapper();

        try {
            User currentUser = (User) request.getSession().getAttribute("currentUser");
            long uid = currentUser.getId();
            String shopId = "shopId_" + uid;
            String shopVoStr = (String) request.getServletContext().getAttribute(shopId);
            List<ShopGoodsVo> shopGoodsVos = null;
            if (StringUtils.isNotBlank(shopVoStr)){
                shopGoodsVos = om.readValue(shopVoStr, List.class);
            }else
            {
                shopGoodsVos = new ArrayList<>();
            }

            request.setAttribute("shopGoodsVos",shopGoodsVos);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "shoppingCar";
    }

    public String add(HttpServletRequest request, HttpServletResponse response) {
        ObjectMapper om = new ObjectMapper();
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        long uid = currentUser.getId();
        String shopId = "shopId_" + uid;
        String shopVo = (String) request.getServletContext().getAttribute(shopId);
        List<ShopGoodsVo> shopGoodsVos = null;
        try {
            if (StringUtils.isNotBlank(shopVo)) {
                shopGoodsVos = (List<ShopGoodsVo>) om.readValue(shopVo, List.class);
                shopGoodsVos.add(shopGoodsVo);
            } else {
                shopGoodsVos = new ArrayList<>();
                shopGoodsVos.add(shopGoodsVo);
            }
            request.getServletContext().setAttribute(shopId,om.writeValueAsString(shopGoodsVos));
            request.setAttribute("shopGoodsVos",shopGoodsVos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "shoppingCar";
    }

    public String pay(HttpServletRequest request, HttpServletResponse response) {
        return null;
    }

    @Override
    public ShopGoodsVo getModel() {
        return shopGoodsVo;
    }
}

index.js

$(function(){

  var  ctx=$("#ctx").val();
  
  //加载左侧书籍类别
  $.ajax({
	   url:ctx+'/categroy.action?methodName=comboBox',
	   success:function(data){//使用success的回调函数
		   data=eval('('+data+')');//得到的是一个josn对象
		   //debugger;
		   //alert(data);
		   //<li class="list-group-item">现代言情</li>
	      for(i in data){
	    	  $(".list-group").append('<li class="list-group-item" οnclick="searchByType('+data[i].id+')">'+data[i].name+'</li>');
	    	  $(".c-category li").eq(0).addClass('bg-color1');
		      $(".c-category li:gt(0)").addClass('bg-color2');
		      $(".c-category li:gt(0)").hover(function() {
					$(this).addClass('bg-opacity');
				},function() {
					$(this).removeClass('bg-opacity');
			});
	      }
	   }
   });
   
//按照书籍类别搜索
function searchByType(cid){
	 var  ctx=$("#ctx").val();
	 location.href=ctx+"/book.action?methodName=search&cid="+cid;
}
//mhnr

 $(".list-group-item:gt(0)").hover(function () {
     // $(this).siblings().removeClass('list-group-item-hover');
     $(this).addClass('list-group-item-hover');
 }, function () {
     $(this).removeClass('list-group-item-hover');
 });
后面渲染的元素节点
$(".list-group").on('mouseenter','.list-group-item:gt(0)',function () {
    $(this).addClass('list-group-item-hover');
});

$(".list-group").on('mouseleave','.list-group-item:gt(0)',function () {
    $(this).removeClass('list-group-item-hover');
});


//分类
$.ajax({
    url: '${pageContext.request.contextPath}/category.action?methodName=combobox',
    success: function (data) {
        data = eval('('+data+')');
        // debugger;
        for (i in data) {
            $(".list-group").append('<li onclick="searchByType('+ data[i].id+')" class="list-group-item">' + data[i].name + '</li>');
        }
    }
});
//加载新书
$.ajax({
	url:ctx+'/book.action?methodName=news',
	success:function(data){
		data = eval('('+data+')');
//		给news container 所属的div添加row或者列
		
		appendBookDiv($(".news"),data.data,0,"");
	}
});

//加载热销书籍
$.ajax({
	url:ctx+'/book.action?methodName=hots',
	success:function(data){
		data = eval('('+data+')');
//		给news container 所属的div添加row或者列
		appendBookDiv($(".hots"),data.data,0,"");
	}
});

})

/*
* 1、给哪个div追加html内容(jquery对象)
* 2、最佳内容的数据来源
* 3、标识当前是第几行内容
* 4、最终追加的html
*/
function appendBookDiv($node,data,level,htmlstr){
//第一行:0-5
var start = level * 6;

//data的数据12条
var len = data.length;
htmlstr += '<div class="row book">';
for(i=start;i<start+6;i++){
	if(i==len) break;
	htmlstr += '<div class="col-sm-2" style="width: 90px;">';
	htmlstr += '<img src="'+data[i].image+'" >';
	htmlstr += '<p>'+data[i].name+'</p>';
	htmlstr += '<b>¥'+data[i].price+'</b>';
	htmlstr += '</div>';
}
htmlstr += '</div>';
level++;
if(start+6>=len){
	$node.append(htmlstr);
}else{
	appendBookDiv($node,data,level,htmlstr);
}
//mhnr



//书籍搜索
function search(){
	 var  ctx=$("#ctx").val();
	 location.href=ctx+"/book.action?methodName=search&name="+$("#book_name").val();
}
}


mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>	

	<!--书籍-->
	<action path="/book"       type="com.wangqiuping.action.BookAction">
	   <forward name="search"   path="/fg/search.jsp" redirect="false" />
	</action>
	
	<!--用户操作 -->
	<action path="/user"   type="com.wangqiuping.action.UserAction">
	
	    <forward name="login"   path="/login.jsp"    redirect="false"/>
	    <forward name="main"    path="/bg/main.jsp"  redirect="false"/>
	    
	</action>
	
    <!--书籍类别加载  -->
    <action path="/categroy"    type="com.wangqiuping.action.CategroyAction">
	
	</action>
	
	<!--购物车  -->
    <action path="/shopping"    type="com.wangqiuping.action.ShoppingAction">
    
	    <forward name="shoppingCar"   path="/fg/shoppingCar.jsp"    redirect="false"/>
	
	</action>
   
</config>

总结

今天的内容就是这么多啦!

猜你喜欢

转载自blog.csdn.net/m0_47906344/article/details/107281337
今日推荐