码迷,mamicode.com
首页 > Web开发 > 详细

实现网站的登陆,注册,查看商品详细信息,加入购物车,注销登陆等简单功能。

时间:2019-04-23 21:20:36      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:sadd   from   join   别名   date()   获取数据   有用   int   print   

创建一个LoginFilter拦截器

@WebFilter("*.do")// 拦截需要进行登陆校验的请求       /home /addCart.do /myCart.do /login /reg

 

// 判断是否登陆
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;

Object user = req.getSession().getAttribute("user");
if(user == null){
//session中没有取到用户信息 证明 没有登录 则跳转到登陆界面
resp.sendRedirect("/shop/views/login.jsp");
}else{
//session中获取到了用户信息 证明 已经登陆 则 放行
filterChain.doFilter(req,resp);
}

 

在网址输入地址进入首页/home/servlet

进行操作:1调用dao获取数据库中所有商品的数据   

        IProductDAO中{List<Map<String,Object>> getAllProduct}

        ProductDAOImpl中{  String sql = "select * from product";       return DBUtil.executeQuery( sql );  }

          IProductDAO dao = new ProductDAOImpl();
          List<Map<String,Object>> allProduct = dao.getAllProduct();

        2请求共享数据

        req.setAttribute( "allProduct",allProduct );

     3请求转发到首页 index.jsp

        req.getRequestDispatcher( "/views/index.jsp" ).forward( req,resp );

     4在index.jsp中用<c:forEach> 对数据进行循环输出

        <c:forEach var="p" items="${allProduct}">
        <div class="products">
         <!--商品图片-->
         <a href="/shop/product?pid=${p.pid}" class="pimg" style="background-image: url(${p.pimage});"></a>
         <div class="info">
         <div class="part">
         <!--商品价格-->
         <div class="price">¥${p.shopPrice}</div>
         <div class="collect">
         <!--商品收藏-->
         <i class="icon-star"></i>${p.collect}
         </div>
         </div>
         <i class="icon-select">
         <!--商品简介-->
         </i>${p.pname}
         </div>
         </div>

        </c:forEach>

 

 

查看商品详细信息:在首页点击图片 根据图片对应的ID 进行查询所有信息  

                 在index.jsp中图片设置成<a>标签 跳转  并设置跳转属性根据pid    href="/shop/product?pid=${p.pid}"

在ProductServlet中进行操作:

            try{

1 获取请求参数pid    String pid = req.getParameter( "pid" );

             2 在dao中根据pid查询商品信息

              IProductDAO中{   Map<String,Object> getProduct(int pid);   }

              ProductDAOImpl中{String sql = "select * from product where pid = ?";     List<Map<String, Object>> list = DBUtil.executeQuery( sql,pid );     if(list.size()>0){   return list.get( 0 );   }  return null;   }

              IProductDAO productDAO = new ProductDAOImpl();

                Map<String, Object> product = productDAO.getProduct( Integer.parseInt( pid ) );

             3 共享数据

              req.setAttribute( "product",product );

             4 请求转发到product.jsp  商品详细信息页面

               req.getRequestDispatcher( "/views/product.jsp" ).forward( req,resp );

            }catch(Exception e){System.out.println("程序出错了");   resp.sendRedirect( "/views/index.jsp" ); }  

            注: 这里try catch 是因为如果pid我输入字符串会出BUG  所以这里直接处理异常 重定向到index.jsp 首页即可

              

 

      在product.jsp页面中

<c:choose>
<%--if(商品为空 ){--%>
<c:when test="${empty product}">
<h1>对不起 暂无该商品</h1>
</c:when>

<%--else{ --%>
<c:otherwise>
<div class="wrap">
<img src="${product.pimage}" />
<div class="description">

<form action="/shop/addCart" method="post">
<h2>"${product.pname}</h2>
<div class="old_price">
原价:
<span>
¥${product.marketPrice}
</span>
</div>
<div class="price">
折扣价:
<span>
¥${product.shopPrice}
</span>
</div>

<div>
尺码:均码
</div>

<div class="count">
数量:
<span class="s">-</span>
<input type="text" value="1" name="num" class="num" />
<span class="s">+</span>
</div>

<input type="hidden" name="pid" value="${product.pid}" />

<div>
<input type="submit" value="加入购物车" class="goods_cart" />
</div>

<div>
<input type="submit" value="立即购买" class="buy"/>
</div>
</form>
</div>

</div>

</c:otherwise>

</c:choose>

 

<c:choose> 选择 <c:when 判断 ¥{empty  product}> 如果超出 则显示商品不存在 

 

                                    注册

 

在header.jsp中给注册设置成<a> 标签   点击时 直接跳转到registr.jsp页面中

当我点击注册时 跳转到RegisterServlet 

    1:设置编码格式    req.setCharacterEncoding( "UTF-8" );

     2:获取请求参数

String username = req.getParameter("username");

String password = req.getParameter("password");

String telephone = req.getParameter("telephone");

String nickname = req.getParameter("nickname");

String email = req.getParameter("email");

    3:验证用户名是否已经被注册  唯一性效验

    在IUserDAO中{   boolean isExist(String username);   }

    在UserDAOImpl中{   String sql = "select * from user where username = ?";  List<Map<String, Object>> list = DBUtil.executeQuery(sql, username);   return list.size()>0;   }

          IUserDAO userDAO = new UserDAOImpl();
          boolean exist = userDAO.isExist( username );

 

        if(exist){

            //3 如果用户名已经被注册 提示用户 用户名被占用
         req.setAttribute("error","用户名已经被占用"); 在register.jsp页面中写入一个
${error};
       }else {
          //4 没有注册 则 将用户信息添加到数据库中
          在IUserDAO中{boolean saveUser(User user);  }
          在UserDAOImpl中{
String sql = "insert into user(telephone,password,username) values (?,?,?)";
          return DBUtil.executeUpdate( sql,user.getTelephone(),user.getPassword(),user.getUsername() ); } 

        User user = new User(0, username, password, nickname, email, telephone);
            userDAO.saveUser(user);
        req.setAttribute("success","注册成功"); }
          
//5 请求转发到注册界面
          
req.getRequestDispatcher("/views/register.jsp").forward(req,resp);




                        在register.jsp页面中写入



          <script>
             if("${success}" == "注册成功"){

           if(confirm("注册成功是否去登陆")){
                    window.location.href = "/shop/views/login.jsp";
           }
          }
           </script>
                注册成功后弹出一个警告框  
    
                          
                            登陆操作
在header.jsp中点击登陆 跳转到login.jsp页面。 在login.jsp页面中点击登陆 跳转到LoginServlet
1:获得数据
String username = req.getParameter( "username" ); String password = req.getParameter( "password" );
2:验证账号密码是否正确
IUserDAO userDAO = new UserDAOImpl();


在IUserDAO中{ Map<String,Object> isLogin(String username,String password); }
在UserDAOImpl中{
String sql = "select * from user where username = ? and password = ?";

           List<Map<String, Object>> list = DBUtil.executeQuery(sql, username, password);
            if(list.size()>0){
            return list.get( 0 );
            }
            return null;


Map<String, Object> user  = userDAO.isLogin(username, password);

判断 : if(user==null){
      // 3 如果不正确  请求转发到  login.jsp 并 提示 账号或密码不正确
      req.setAttribute("error","对不起用户名或密码不正确");
      req.getRequestDispatcher("/views/login.jsp").forward(req,resp); 在login.jsp 页面中 写入 ${error} 提示 错误
      }else{
        // 4 如果正确  重定向到  servlet
       HttpSession session = req.getSession();//获取session对象 session 可在多页面直接显示登陆后的信息。
       session.setAttribute("user",user);
     // 5 重定向到查询所有商品后的首页
      resp.sendRedirect("/shop/home");}


         在header.jsp页面中把 登陆注册换成
            <c:choose>
            <c:when test="${empty user}"> // 判断用户名是否为空
            <li><a href="/shop/views/login.jsp">登录</a></li>
            <li><a href="/shop/views/register.jsp">注册</a></li>
             </c:when>
             <c:otherwise> // 不为空显示用户别名
             <li>欢迎尊敬的VIP:<a href="/shop/views/persional.jsp">${user.nickname}</a></li>
             </c:otherwise>
            </c:choose>
  

                              注销操作

点击用户别名 进入到个人中心 persional.jsp 页面中  点击注销 跳转到LogOutServlet中
步骤:    
req.getSession().invalidate(); //销毁session 销毁之后 相当于 将登陆信息全部清除
 resp.sendRedirect( "/shop/home" );        //  重定向到主页

                        



                                添加到购物车

需要在product.jsp页面中 添加    <input type="hidden"  name="pid"  value="${product.pid}" />   得到pid的值


在商品详细信息页面点击添加购物车 跳转到AddCartServlet中

1: 判断房前是否有用户登陆
Map user = (Map) req.getSession().getAttribute("user");

2: 获取商品信息关于pid 数量num 跟用户uid
String pid = req.getParameter("pid");

String num = req.getParameter("num");
Integer uid = (Integer) user.get("uid");
3: 调用dao层中的方法
IProductDAO productDAO = new ProductDAOImpl();
4:判断:
     在IProductDAO中{ boolean isAddCart(String pid,Integer uid); } 
     在ProductDAOImpl中{
String sql = "select * from car where pid = ? and uid = ?";
                 List<Map<String, Object>> list = DBUtil.executeQuery( sql,pid,uid );
                  return list.size()>0;
}
if (productDAO.isAddCart(pid, uid)) {   //  如果用户与商品存在 

  
        
          在IProductDAO中{   boolean  updateCart(String pid,String num,Integer uid);   } 
           在ProductDAOImpl中{String sql = "update car set num = num+? where uid = ? and pid = ?";
                    return DBUtil.executeUpdate(sql,num,uid,pid);}
        // 修改购物车中商品信息
productDAO.updateCart(pid, num, uid);
} else {



在IProductDAO中{   boolean  addCart(String pid,String num,Integer uid);   }
在ProductDAOImpl中{   String sql = "insert into car (uid,pid,num) values (?,?,?)";
             return DBUtil.executeUpdate(sql,uid,pid,num);}
        //不存在就直接添加商品到购物车
productDAO.addCart(pid, num, uid);
}
5: 共享数据
req.setAttribute("success", "添加成功");
6:转发到详细商品信息的ProductServlet
req.getRequestDispatcher("/product").forward(req, resp);

}


在 product.jsp页面中写入
<script>

if("${error}" != ""){
if(confirm("对不起 您还没有登陆 是否去登录")){
window.location.href = "/shop/views/login.jsp";
}
}

if("${success}" != ""){
if(confirm("添加成功 是否去购物车")){
window.location.href = "/shop/views/goodscart.jsp";
}
}


</script> 如果用户不存在 提示是否去登陆界面 存在 提示是否去购物车页面






                          进入我的购物车

在header.jsp页面中 点击购物车跳转到MyCartServlet中

1: 判断用户是否登陆 Map user = (Map) req.getSession().getAttribute("user");

2: 如果登陆了则
获取用户的 uid ----》 根据uid 获取用户的购物车商品

Integer uid = (Integer) user.get("uid");

IUserDAO userDAO = new UserDAOImpl();

    在IUserDAO中{
List<Map<String,Object>> getMyCart(Integer uid); }
    在UserDAOImpl中{
    String sql = "select p.pid ,p.pimage,p.pname,p.shopPrice,c.num  " +
"from car c " +
"INNER JOIN product p " +
"on c.pid = p.pid " +
"where c.uid = ? ";

  return DBUtil.executeQuery(sql,uid); }
List<Map<String, Object>> myCart = userDAO.getMyCart(uid);

3: 共享数据
req.setAttribute("myCart", myCart);
4:
请求转发到 goodscart.jsp 展示数据
    req.getRequestDispatcher("/views/goodscart.jsp").forward(req, resp);




在goodscart.jsp 页面中

<c:choose>
<c:when test="${empty myCart}">

<h1>对不起 您的购物车 空空如也 请先去 <a href="/shop/home">购物</a> </h1>

</c:when>
<c:otherwise>

<c:forEach var="p" items="${myCart}">
<div class="goods">
<ul>
<li><img src="${p.pimage}"/> ${p.pname}</li>
<li>尺碼:均碼</li>
<li class="price">${p.shopPrice}</li>
<li>
<div class="count">
<span class="s">-</span>
<input type="text" value="${p.num}" name="num" class="num" />
<span class="s">+</span>
</div>
</li>
<li class="subtotal">76</li>
<li>
<a href="#">刪除</a>
</li>
</ul>
</div>
</c:forEach>

</c:otherwise>

</c:choose>



                                删除购物车中的商品

在购物车中点击删除按钮 跳转到DeleteServlet中
1:获取oid的信息 String oid = req.getParameter( "oid" );
2:通过dao层删除
在IUserDAO中{ boolean deleteCart(int oid); }
在UserDAOImpl中{
String sql = "delete from car where oid = ?"; return DBUtil.executeUpdate( sql,oid ); }

IUserDAO dao = new UserDAOImpl();

dao.deleteCart(Integer.parseInt( oid ));
3:重定向到购物车页面
resp.sendRedirect( "/shop/mycart.do" );      注:删除不了商品检查多表联合查询时是否查询了oid的信息
 


 


 

                                                    



















          
 

 

实现网站的登陆,注册,查看商品详细信息,加入购物车,注销登陆等简单功能。

标签:sadd   from   join   别名   date()   获取数据   有用   int   print   

原文地址:https://www.cnblogs.com/LFY001023/p/10754315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!