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


    创建一个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>
                    注册成功后弹出一个警告框  
        
                          
    AJAX写登录操作
        
                                登陆操作
    在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);
    resp.setContentType( "text/json;charset=utf-8" );
    PrintWriter writer = resp.getWriter();
    HashMap<Object, Object> map = new HashMap<>();





    判断 : if(user==null){

          map.put( "code","100404" );
          map.put( "message","对不起,账号密码错误" );
          }else{

          HttpSession session = req.getSession();
          session.setAttribute( "user",user );
          String s = JSON.toJSONString( map );
          writer.write( s );
          writer.close();
     


             在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>
      login.jsp中


    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"+"views/";
    %>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <!DOCTYPE HTML >
    <html>
    <head>
    <base href="<%=basePath%>">

    <title>登录 - 贵美·商城</title>
    <link rel="stylesheet" type="text/css" href="css/login.css"/>
    </head>
    <body>

    <div class="wrap">
    <div class="guimeilogo"></div>

    <div class="login">

    <div class="top">
    <h1>贵美商城</h1>
    <a href="/shop/views/register.jsp">新用户注册</a>
    </div>

    <div class="mid">

    <form>
    <div id="showlogin"></div>
    <input type="text" name="username" id="username" placeholder="用户名" required="required" />
    <input type="text" name="password" id="password" placeholder="密码" required="required" />
    <div id="showdl"></div>
    <input type="button" id="dlsubmit" value="立即登录"/>
    </form>
    </div>

    </div>

    </div>



    </body>


    <script src="js/jquery-2.1.0.js"></script>
    <script>
    dlsubmit.onclick=function () {
    $.post("/shop/login",{"username":username.value,"password":password.value},function (data) {
    if(data.code=="100404"){
    $("#showdl").html(data.message).css("color","red");
    }else{
    window.location.href="/shop/home";
    }
    });
    }
    </script>

    </html>






                                  注销操作

    点击用户别名 进入到个人中心 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的信息
     
            


                                    删除购物车中所有商品

    在购物车中点击删除全部按钮, 跳转到DeleteAllServlet中
    1:获取uid的信息 Map user = (Map) req.getSession().getAttribute( "user" ); Integer uid = (Integer) user.get( "uid" );
    2:通过dao删除所有商品
    在IUserDAO中{
    boolean deleteAllCart(int uid); }
    在UserDAOImpl中{
    String sql = "delete from car where uid = ?"; return DBUtil.executeUpdate( sql,uid ); }

    IUserDAO dao = new UserDAOImpl();

    dao.deleteCart(Integer.parseInt( oid ));
    3:重定向到购物车页面。
    resp.sendRedirect( "/shop/mycart.do" );
     
                                      修改密码功能

    在个人中心页面,点击修改密码跳转到修改密码 update.jsp页面。点击提交修改 跳转到UpdatePasswordServlet中
    步骤:1 获取用户uid信息 Map user = (Map) req.getSession().getAttribute( "user" );
    得到uid:
    Integer uid = (Integer) user.get( "uid" );
                 在得到用户的密码: String password1 = (String) user.get( "password" );
                 在得到用户在网页上输入的老密码: String oldpassword = req.getParameter( "oldpassword" );
                 在得到用户在商业上输入的新密码: String newpassword = req.getParameter( "newpassword" );
              判断: 如果 用户密码 等于网页上输入的老密码 则修改成功 否则修改失败
                

                  if(oldpassword.equals(password1)){ 注:这里需要判断的是两个字符串是否相等所以用equals判断
                   IUserDAO dao = new UserDAOImpl();
                  dao.updatePassword( newpassword,uid );
                   req.setAttribute( "success","修改成功" );
                  }else{
                   req.setAttribute( "error","修改失败" );
                  }
                  req.getRequestDispatcher( "/views/update.jsp" ).forward( req,resp );
    
    
     


     

                                                        



















              
     
  • 相关阅读:
    Html5——视频标签使用
    Android的四大组件
    Android 硬编码
    按键事件处理
    android Keycode 完全对照表
    Activity的生命周期
    音乐播放控制
    Android permission 访问权限大全
    制作留言板相关资料
    adb查询log命令
  • 原文地址:https://www.cnblogs.com/LFY001023/p/10754315.html
Copyright © 2020-2023  润新知