java-web京东购物网 加入购物车与查看购物车的实现运用session服务器端(在数据库中查询)

来源:互联网 发布:淘宝支付怎么用微信 编辑:程序博客网 时间:2024/04/28 22:38

标题:加入购物车与查看购物车的实现运用session,运用getId的方法获取session的id值,            设置到cookie中,与session的id值一样,设置页面延长的时间,加入到reponse响应中,            运用IE11验证, 页面关闭后,购物车与查看购物车的信息,依然存在,实现共享。1.封装一个从数据库表中映射来的商品类Goodspublic class Goods implements Serializable {private static final long serialVersionUID = 1L;private Integer id;  //商品idprivate String  name;  //商品名称private Double price;  //商品价格private Date addDate;  //商品日期private String img;  //商品图片private String number; //商品编号public Goods() {super();// TODO Auto-generated constructor stub}public Goods(Integer id, String name, Double price, Date addDate,String img, String number) {super();this.id = id;this.name = name;this.price = price;this.addDate = addDate;this.img = img;this.number = number;}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 Double getPrice() {return price;}public void setPrice(Double price) {this.price = price;}public Date getAddDate() {return addDate;}public void setAddDate(Date addDate) {this.addDate = addDate;}public String getImg() {return img;}public void setImg(String img) {this.img = img;}public String getNumber() {return number;}public void setNumber(String number) {this.number = number;}@Overridepublic String toString() {return "Goods [id=" + id + ", name=" + name + ", price=" + price+ ", addDate=" + addDate + ", img=" + img + ", number="+ number + "]";}}2. 封装了一个接口类BaseDao,封装了方法public interface BaseDao<T,PK> {根据id查询实体T findByID(PK id);查询所有List<T> findAll();}3.封装了一个接口GoodsDao,继承了BaseDaopublic interface GoodsDao extends BaseDao<Goods, Integer>{}4.封装一个GoodsDao的实现类GoodsDaoImpl,实现了GoodsDao的所有方法    // 数据库操作的有关对象声明private Connection conn;    //数据库操作对象(得到预处理对象)private PreparedStatement pstmt;   //返回的结果集private ResultSet rs;public class GoodsDaoImpl implements GoodsDao {    //根据id查询实体    @Overridepublic Goods findByID(Integer id) {        Goods entity = null;// 获取连接对象conn = DBConn.getConn();// 第二步:定义sql语句        String sql = "select id,name,price,adddate,number,img from goods where id=?";try {        //第三步:根据sql语句获取预处理对象pstmt = conn.prepareStatement(sql);         //第四步:为占位符赋值int index=1;pstmt.setInt(index++, id);         //第六步:执行查询(返回rs结果集)rs = pstmt.executeQuery();         //判断if (rs.next()) {            //创建对象entity = new Goods();            //为对象赋值entity.setId(rs.getInt("id"));entity.setName(rs.getString("name"));entity.setPrice(rs.getDouble("price"));entity.setImg(rs.getString("img"));entity.setAddDate(rs.getDate("adddate"));entity.setNumber(rs.getString("number"));}DBConn.release(pstmt, rs);} catch (SQLException e) {e.printStackTrace();}return entity;  }  //查询所有  @Overridepublic List<Goods> findAll() {List<Goods> entities = new ArrayList<Goods>();// 获取连接对象conn = DBConn.getConn();// 第二步:定义sql语句String sql = "select id,name,price,adddate,number,img from goods";try {pstmt = conn.prepareStatement(sql);rs = pstmt.executeQuery();while (rs.next()) {Goods entity = new Goods();entity.setId(rs.getInt("id"));entity.setName(rs.getString("name"));entity.setPrice(rs.getDouble("price"));entity.setImg(rs.getString("img"));entity.setAddDate(rs.getDate("adddate"));entity.setNumber(rs.getString("number"));entities.add(entity);}DBConn.release(pstmt, rs);} catch (SQLException e) {e.printStackTrace();}return entities;}   }}5.封装一个条目CartItem方法public class CartItem implements Serializable {private static final long serialVersionUID = 1L;private Goods goods;//购买的商品private Integer count;//购买商品的数量public CartItem() {super();// TODO Auto-generated constructor stub}public CartItem(Goods goods, Integer count) {super();this.goods = goods;this.count = count;}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;}@Overridepublic String toString() {return "CartItem [goods=" + goods + ", count=" + count + "]";}    }6.封装一个CartItemDao的接口类public interface CartItemDao {    //根据map集合对象获取所有购物车中商品信息public List<CartItem> findAll(Map map);}7.封装一个CartItemDao的实现类CartItemDaoImpl,实现了CartItemDao中根据map集合对象获取所有购物车中商品信息的方法  public class CartItemDaoImpl implements CartItemDao {    private GoodsDao goodsdao = new GoodsDaoImpl();@Overridepublic List<CartItem> findAll(Map map) {List<CartItem> entities = new ArrayList<CartItem>();//获取map集合key对应的set集合Set<Integer> set = map.keySet();//拿到set集合迭代器Iterator<Integer> it = set.iterator();//遍历while(it.hasNext()){//对应商品的idInteger key = it.next();//对应商品的数量Integer count = (Integer)map.get(key);//根据商品的id去查询商品Goods goods = goodsdao.findByID(key);//创建条目CartItem cartItem = new CartItem(goods,count);//添加到集合中entities.add(cartItem);}return entities;}}8.创建wec.jsp显示购物与查看购物车链接  <a href="${pageContext.request.contextPath}/selectGoods.do?oper=select">购物</a>  <a href="${pageContext.request.contextPath}/listCart.do?oper=list">查看购物车</a>9.创建GoodsServlet(selectGoods.do)后转发到listGoods.jsp  public class GoodsServlet extends HttpServlet {//声明操作对象private GoodsDao goodDao = new GoodsDaoImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//获取oper值String oper = request.getParameter("oper");//判断if("select".equals(oper)){//查询出来List<Goods> entities = goodDao.findAll();//存入到域中request.setAttribute("entities", entities);//转发到request.getRequestDispatcher("./listGoods.jsp").forward(request, response);}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}10.创建(显示)listGoods.jsp页面构建商品信息(商品编号、名称、价格、图片、日期等)  在listGoods.jsp创建  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>   <c:forEach var="entity" items="${entities}">          <div style="float: left; border: solid 1px red; margin-right: 10px; margin-bottom: 10px">             <div>商品编号:${entity.number}</div>             <div>商品名称:${entity.name}</div>             <div>商品价格:${entity.price}</div>             <div>                <input type="button" value="-" onclick="operNum(this)"><input type="text" size="1" value="1" name="num" id="${entity.id}"><input type="button" value="+" onclick="operNum(this)">             </div>             <div><a href="javascript:" onclick="addCart(this)" id="${entity.id}">加入购物车</a></div>          </div>      </c:forEach>11.引入javascript文件cart.js,进行处理(后转发给add.do的CartServlet处理)   通过js文件 获取单件商品的id和随即加减的数量count   //处理 + -按钮  随即增加与减少   function operNum(inputDom){ //声明操作对象的value值 + 或是 - var value = inputDom.value; //声明的是数量对应的dom对象 var numDom; if(value=="+"){numDom = inputDom.previousSibling; numDom.value = eval(numDom.value+"+"+1);}else if(value=="-"){numDom = inputDom.nextSibling;if(numDom.value<=1){numDom.value=1;}else{numDom.value=eval(numDom.value+"-"+1);}};//处理加入购物车function addCart(e){var id=e.id;    var count=1;    //获取所有的输入框的dom对象var inputNumDoms = document.getElementsByName("num");//遍历dom对象for(var i=0;i<inputNumDoms.length;i++){//获取具体的某个对象   var inputDom = inputNumDoms.item(i);   //根据自定义的id的属性值判断与哪个商品的id相同   if(id==inputDom.id){    count=inputDom.value;    break;   }}//发送请求window.location.href="http://localhost:8080/jd/addCart.do?oper=add&id="+id+"&count="+count;}  12.创建加入购物车和查看购物车的Servlet(CartServlet)    public class CartServlet extends HttpServlet {private CartItemDao cartItemDao = new CartItemDaoImpl();public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {//获取请求操作的标示符String oper = request.getParameter("oper");//判断if("add".equals(oper)){//加入购物车//获取商品的idString id = request.getParameter("id");String count = request.getParameter("count");//获取session对象HttpSession session = request.getSession();//页面关闭后购物车和查看购物车的信息还存在//获取session中的id和cookie中的id一样String value = session.getId();//设置cookie中的value值Cookie cookie = new Cookie("JSESSIONID", value);//设置延长时间cookie.setMaxAge(30*60);   cookie.setPath("/jd");//存入到响应中response.addCookie(cookie);//从session中取cart对应数据Map<Integer, Integer> cart = (Map<Integer, Integer>)session.getAttribute("cart");if(cart!=null){//第二次存的时候、首先判断这个商品已经存入过了if(cart.containsKey(Integer.parseInt(id))){//如果含有、现在的数量加上原有的数量存入cart.put(Integer.valueOf(id),cart.get(Integer.valueOf(id))+Integer.valueOf(count));}else{//如果没有立即存入//把商品的id和商品的数量存入到map集合中 id作为key count作为value值cart.put(Integer.parseInt(id), Integer.parseInt(count));}}else{ //首先创建一个map集合对象cart = new LinkedHashMap<Integer, Integer>();//把商品的id和商品的数量存入到map集合中 id作为key count作为value值cart.put(Integer.parseInt(id), Integer.parseInt(count));}//存入到session中session.setAttribute("cart", cart);//根据id查询实体List<CartItem> entities = cartItemDao.findAll(cart);//存入到request中request.setAttribute("entities", entities);//转发到listCart.jsp页面request.getRequestDispatcher("./listCart.jsp").forward(request, response);}else if("list".equals(oper)){//查看购物车listCart(request, response);}}    //查看购物车private void listCart(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {//获取session对象HttpSession session = request.getSession();//从session中取cart对应数据Map<Integer, Integer> cart = (Map<Integer, Integer>)session.getAttribute("cart");if(cart!=null){//把map集合遍历,获取所有的购买过的商品信息List<CartItem> entities = cartItemDao.findAll(cart);//存入到request中request.setAttribute("entities", entities);request.getRequestDispatcher("./listCart.jsp").forward(request, response);}else{System.out.println("购物车中没有商品");}}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}13 创建显示购物车与查看购物车的页面listCart.jsp  <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  <body>  <div >        <table align="center" style="border: solid; text-align: center">        <tr>           <th><input type="checkbox"></th>           <th>商品名称</th>           <th>商品图片</th>           <th>商品价格</th>           <th>商品数量</th>           <th>操作</th>        </tr>       <c:forEach var="entity" items="${entities}">         <tr>           <td><input type="checkbox"></td>            <td>${entity.goods.name}</td>            <td>${entity.goods.img}</td>              <td>${entity.goods.price}</td>             <td>${entity.count}</td>             <td><a href="">删除</a></td>             </tr>       </c:forEach>       </table>     </div>  </body> 


1 0
原创粉丝点击