JavaWeb項目--網上商城 (6-1)


   day1

1.項目分析

商城實體:     用戶     商品     訂單     分類
實體關系:    用戶和訂單:一對多  商品和訂單:多對多   分類和商品:一對多 
今日任務:    用戶模塊開發  注冊  用戶激活   用戶登錄   用戶退出

 

2.新建項目   導入jar包      驅動 c3p0 dbutils beanutils jstl mail    導入配置文件和工具類      導入頁面
3.新建包結構:
                                        com.itheima.service  
                                        com.itheima.service.impl //處理業務包
                                        com.itheima.dao
                                        com.itheima.dao.impl   //model層處理數據庫
                                        com.itheima.web.servlet  //控制類、control
                                        com.itheima.web.filter    //處理類
                                        com.itheima.domain    //實體類
                                        com.itheima.utils         //工具類
                                        com.itheima.constant  //常量類

4.servlet抽取:    前三條是弊端

                          1.doget每次請求都會執行--- 重寫service
                          2.用了大量 if else if 判斷執行的是那個方法讓方法執行
                                           Method method = this.getClass().getMethod(mt, HttpServletRequest.class,HttpServletResponse.class);
                                           method.invoke(this, request,response);
                          3.每個方法執行的結果無非就是請求轉發或者重定向或者打印數據   讓所有的方法都返回一個字符串  若最后的結果需要請求轉發,就把轉發的路徑給返回
                                    若最后的結果不需要請求轉發,就返回一個null

                              Method method = this.getClass().getMethod(mName, HttpServletRequest.class,HttpServletResponse.class); 
                                 //3.讓方法執行,接受返回值
                             String path=(String) method.invoke(this, request,response);

                            4.所有servlet的service中的代碼都一樣   向上繼續抽取編寫一個BaseServlet,將之前service方法中的代碼復制過來即可, 然所有的servlet都繼承baseservlet即可
                             5.統一的錯誤頁面 

5.  模塊實現         

   數據庫用戶表字段:  user表   uid  用戶主鍵id   username、password、name、email、telephone、birthday、sex、

                                     state、用戶狀態是否激活  0未激活 1激活      code 根據此激活狀態碼

   案例1-用戶注冊

                              1.設置默認首頁(index.jsp),讓其自動的跳轉到/jsp/index.jsp

                              2.修 改index.jsp上的 注冊 連接<a href='/store/user?method=registUI'>注冊</a>
                              3.在userservlet中編寫reigstUI方法 請求轉發到 /jsp/register.jsp
                              4.修改register.jsp上的表單信息action ="/store/user?method=regist"  method為每一個子標簽添加name屬性
                              5.點擊注冊按鈕 向userservlet發送請求
                              6.userservlet中編寫regist方法 獲取參數,封裝成user對象調用service完成注冊 生成提示信息,轉發 /jsp/msg.jsp
                              7.userservice中的操作:調用dao完成注冊操作發送郵件
                              8.userdao...

    案例2-用戶激活
                需求 :     用戶登錄郵箱之后,點擊郵箱中的連接,完成用戶激活操作
                步驟分析:
                              1.點擊郵箱中的連接 ,向商城userservlet發送一個請求 user?method=active&coed=xxxx
                              2.在userservlet中編寫active方法接受code 調用service完成激活 返回值:user 生成提示信息 轉發
                              3.在service中編寫激活方法 通過code獲取用戶 若沒有找到:提示重新激活或者重新注冊若找到了 設置激活狀態 1將code設置為null
                              4.在dao需要編寫兩個方法 getByCode  update

    案例3-用戶登錄

                 需求:    在一個登錄頁面上,輸入用戶名和密碼,點擊登錄,完成登錄操作  隨機驗證碼實現

         步驟分析:

                              1.在index.jsp點擊 登錄 連接,跳轉到登錄頁面

                      2.在userserlvet中編寫 loginUI

                              3.修改login.jsp表單的信息  action: /user?method=login  method   給子標簽添加name屬性

                              4.點擊提交發送請求

                      5.在userservlet中編寫login方法 獲取用戶名和密碼  調用service完成登錄 返回值:user  若登錄成功,跳轉到index.jsp 並展示用戶信息 若登錄失敗,

               若user為空:提示 用戶名和密碼 跳轉到login.jsp  若user不為空但是未激活:提示信息 "請先去郵箱激活,再登錄" 跳轉msg.jsp

               6.service,dao

  案例4-用戶退出

              需求:        點擊 index.jsp上 退出連接,退出當前的用戶,跳轉index.jsp

     步驟分析: 

                              1.點擊 index.jsp上 退出 連接,向userservlet發送請求  /user?methode=logout

                              2.在userservlet中編寫logout方法  銷毀session  重定向到index.jsp

   案例5- 擴展 記住用戶名:

    需求:  登錄成功之后,若勾選了記住用戶名,下一次再登錄的時候,會展示出來用戶名

           步驟分析:修改login方法的邏輯    登錄成功之后,判斷是否勾選了記住用戶名 

            若勾選了,將用戶名(將用戶名編碼)保存到cookie中   在login.jsp加載成功的時候需要從cookie中獲取用戶名且展示出來

  案例6--baseservlet的抽取

6.代碼區 

   

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <filter>
    <filter-name>EncodingFilter</filter-name>
    <filter-class>com.itheima.web.filter.EncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>EncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <servlet>
    <description></description>
    <display-name>UserServlet</display-name>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.itheima.web.servlet.UserServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/user</url-pattern>
  </servlet-mapping>
  <servlet>
    <description></description>
    <display-name>BaseServlet</display-name>
    <servlet-name>BaseServlet</servlet-name>
    <servlet-class>com.itheima.web.servlet.base.BaseServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>BaseServlet</servlet-name>
    <url-pattern>/base</url-pattern>
  </servlet-mapping>
  <error-page>
      <error-code>500</error-code>
      <location>/500.jsp</location>
  </error-page>
  <error-page>
      <error-code>404</error-code>
      <location>/404.jsp</location>
  </error-page>
</web-app>
web.xml
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        response.sendRedirect(request.getContextPath()+"/jsp/index.jsp");
    %>
</body>
</html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>

    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>WEB01</title>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" />
        <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type="text/javascript"></script>
    </head>

    <body>
        <div class="container-fluid">

            <!--
                時間:2015-12-30
                描述:菜單欄
            -->
            <div class="container-fluid">
                <div class="col-md-4">
                    <img src="${pageContext.request.contextPath}/img/logo2.png" />
                </div>
                <div class="col-md-5">
                    <img src="${pageContext.request.contextPath}/img/header.png" />
                </div>
                <div class="col-md-3" style="padding-top:20px">
                    <ol class="list-inline">
                        <c:if test="${empty user }">
                            <li><a href="${pageContext.request.contextPath }/user?method=loginUI">登錄</a></li>
                            <li><a href="${pageContext.request.contextPath }/user?method=registUI">注冊</a></li>
                        </c:if>
                        <c:if test="${not empty user }">
                            ${user.name }:你好!
                            <li><a href="${pageContext.request.contextPath }/user?method=registUI">我的訂單</a></li>
                            <li><a href="${pageContext.request.contextPath }/user?method=logout">退出</a></li>
                        </c:if>
                        <li><a href="cart.htm">購物車</a></li>
                    </ol>
                </div>
            </div>
            <!--
                時間:2015-12-30
                描述:導航條
            -->
            <div class="container-fluid">
                <nav class="navbar navbar-inverse">
                    <div class="container-fluid">
                        <!-- Brand and toggle get grouped for better mobile display -->
                        <div class="navbar-header">
                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                                <span class="sr-only">Toggle navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            <a class="navbar-brand" href="#">首頁</a>
                        </div>

                        <!-- Collect the nav links, forms, and other content for toggling -->
                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav">
                                <li class="active"><a href="product_list.htm">手機數碼<span class="sr-only">(current)</span></a></li>
                                <li><a href="#">電腦辦公</a></li>
                                <li><a href="#">電腦辦公</a></li>
                                <li><a href="#">電腦辦公</a></li>
                            </ul>
                            <form class="navbar-form navbar-right" role="search">
                                <div class="form-group">
                                    <input type="text" class="form-control" placeholder="Search">
                                </div>
                                <button type="submit" class="btn btn-default">Submit</button>
                            </form>

                        </div>
                        <!-- /.navbar-collapse -->
                    </div>
                    <!-- /.container-fluid -->
                </nav>
            </div>

            <!--
                作者:ci2713@163.com
                時間:2015-12-30
                描述:輪播條
            -->
            <div class="container-fluid">
                <div id="carousel-example-generic" class="carousel slide" data-ride="carousel">
                    <!-- Indicators -->
                    <ol class="carousel-indicators">
                        <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
                        <li data-target="#carousel-example-generic" data-slide-to="1"></li>
                        <li data-target="#carousel-example-generic" data-slide-to="2"></li>
                    </ol>

                    <!-- Wrapper for slides -->
                    <div class="carousel-inner" role="listbox">
                        <div class="item active">
                            <img src="${pageContext.request.contextPath}/img/1.jpg">
                            <div class="carousel-caption">

                            </div>
                        </div>
                        <div class="item">
                            <img src="${pageContext.request.contextPath}/img/2.jpg">
                            <div class="carousel-caption">

                            </div>
                        </div>
                        <div class="item">
                            <img src="${pageContext.request.contextPath}/img/3.jpg">
                            <div class="carousel-caption">

                            </div>
                        </div>
                    </div>

                    <!-- Controls -->
                    <a class="left carousel-control" href="#carousel-example-generic" role="button" data-slide="prev">
                        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
                        <span class="sr-only">Previous</span>
                    </a>
                    <a class="right carousel-control" href="#carousel-example-generic" role="button" data-slide="next">
                        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
                        <span class="sr-only">Next</span>
                    </a>
                </div>
            </div>
            <!--
                作者:ci2713@163.com
                時間:2015-12-30
                描述:商品顯示
            -->
            <div class="container-fluid">
                <div class="col-md-12">
                    <h2>熱門商品&nbsp;&nbsp;<img src="${pageContext.request.contextPath}/img/title2.jpg"/></h2>
                </div>
                <div class="col-md-2" style="border:1px solid #E7E7E7;border-right:0;padding:0;">
                    <img src="${pageContext.request.contextPath}/products/hao/big01.jpg" width="205" height="404" style="display: inline-block;"/>
                </div>
                <div class="col-md-10">
                    <div class="col-md-6" style="text-align:center;height:200px;padding:0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/middle01.jpg" width="516px" height="200px" style="display: inline-block;">
                        </a>
                    </div>
                
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>

                    <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
                    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>

                    <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>

                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
                </div>
            </div>
            <!--
                作者:ci2713@163.com
                時間:2015-12-30
                描述:廣告部分
            -->
            <div class="container-fluid">
                <img src="${pageContext.request.contextPath}/products/hao/ad.jpg" width="100%"/>
            </div>
            <!--
                作者:ci2713@163.com
                時間:2015-12-30
                描述:商品顯示
            -->
            <div class="container-fluid">
                <div class="col-md-12">
                    <h2>熱門商品&nbsp;&nbsp;<img src="${pageContext.request.contextPath}/img/title2.jpg"/></h2>
                </div>
                <div class="col-md-2" style="border:1px solid #E7E7E7;border-right:0;padding:0;">
                    <img src="${pageContext.request.contextPath}/products/hao/big01.jpg" width="205" height="404" style="display: inline-block;"/>
                </div>
                <div class="col-md-10">
                    <div class="col-md-6" style="text-align:center;height:200px;padding:0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/middle01.jpg" width="516px" height="200px" style="display: inline-block;">
                        </a>
                    </div>
                
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>

                    <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
                    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>

                    <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small03.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
    
                    <div class="col-md-2" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small04.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>

                    <div class="col-md-2 yes-right-border" style="text-align:center;height:200px;padding:10px 0px;">
                        <a href="product_info.htm">
                            <img src="${pageContext.request.contextPath}/products/hao/small05.jpg" width="130" height="130" style="display: inline-block;">
                        </a>
                        <p><a href="product_info.html" style='color:#666'>冬瓜</a></p>
                        <p><font color="#E4393C" style="font-size:16px">&yen;299.00</font></p>
                    </div>
                </div>
            </div>            
            <!--
                作者:ci2713@163.com
                時間:2015-12-30
                描述:頁腳部分
            -->
            <div class="container-fluid">
                <div style="margin-top:50px;">
                    <img src="${pageContext.request.contextPath}/img/footer.jpg" width="100%" height="78" alt="我們的優勢" title="我們的優勢" />
                </div>
        
                <div style="text-align: center;margin-top: 5px;">
                    <ul class="list-inline">
                        <li><a href="info.html">關於我們</a></li>
                        <li><a>聯系我們</a></li>
                        <li><a>招賢納士</a></li>
                        <li><a>法律聲明</a></li>
                        <li><a>友情鏈接</a></li>
                        <li><a>支付方式</a></li>
                        <li><a>配送方式</a></li>
                        <li><a>服務聲明</a></li>
                        <li><a>廣告聲明</a></li>
                    </ul>
                </div>
                <div style="text-align: center;margin-top: 5px;margin-bottom:20px;">
                    Copyright &copy; 2005-2016 傳智商城 版權所有
                </div>
            </div>
        </div>
    </body>

</html>
/jsp/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!doctype html>
<html>
    <head></head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>會員登錄</title>
        <link rel="stylesheet" href="${pageContext.request.contextPath}/css/bootstrap.min.css" type="text/css" />
        <script src="${pageContext.request.contextPath}/js/jquery-1.11.3.min.js" type="text/javascript"></script>
        <script src="${pageContext.request.contextPath}/js/bootstrap.min.js" type="text/javascript"></script>
<!-- 引入自定義css文件 style.css -->
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/style.css" type="text/css"/>

<style>
  body{
   margin-top:20px;
   margin:0 auto;
 }
 .carousel-inner .item img{
     width:100%;
     height:300px;
 }
 .container .row div{ 
     /* position:relative;
     float:left; */
 }
 
font {
    color: #3164af;
    font-size: 18px;
    font-weight: normal;
    padding: 0 10px;
}
 </style>
</head>
<body>




            <!--
                時間:2015-12-30
                描述:菜單欄
            -->
            <div class="container-fluid">
                <div class="col-md-4">
                    <img src="${pageContext.request.contextPath}/img/logo2.png" />
                </div>
                <div class="col-md-5">
                    <img src="${pageContext.request.contextPath}/img/header.png" />
                </div>
                <div class="col-md-3" style="padding-top:20px">
                    <ol class="list-inline">
                        <li><a href="login.htm">登錄</a></li>
                        <li><a href="register.htm">注冊</a></li>
                        <li><a href="cart.htm">購物車</a></li>
                    </ol>
                </div>
            </div>
            <!--
                時間:2015-12-30
                描述:導航條
            -->
            <div class="container-fluid">
                <nav class="navbar navbar-inverse">
                    <div class="container-fluid">
                        <!-- Brand and toggle get grouped for better mobile display -->
                        <div class="navbar-header">
                            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
                                <span class="sr-only">Toggle navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            <a class="navbar-brand" href="#">首頁</a>
                        </div>

                        <!-- Collect the nav links, forms, and other content for toggling -->
                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav">
                                <li class="active"><a href="#">手機數碼<span class="sr-only">(current)</span></a></li>
                                <li><a href="#">電腦辦公</a></li>
                                <li><a href="#">電腦辦公</a></li>
                                <li><a href="#">電腦辦公</a></li>
                            </ul>
                            <form class="navbar-form navbar-right" role="search">
                                <div class="form-group">
                                    <input type="text" class="form-control" placeholder="Search">
                                </div>
                                <button type="submit" class="btn btn-default">Submit</button>
                            </form>

                        </div>
                        <!-- /.navbar-collapse -->
                    </div>
                    <!-- /.container-fluid -->
                </nav>
            </div>





<div class="container" style="width:100%;background:url('${pageContext.request.contextPath}/image/regist_bg.jpg');">
<div class="row"> 

    <div class="col-md-2"></div>
    
    


    <div class="col-md-8" style="background:#fff;padding:40px 80px;margin:30px;border:7px solid #ccc;">
        <font>會員注冊</font>USER REGISTER
        <form class="form-horizontal" style="margin-top:5px;" method="post" action="${pageContext.request.contextPath }/user">
            <input type="hidden" name="method" value="regist">
             <div class="form-group">
                <label for="username" class="col-sm-2 control-label">用戶名</label>
                <div class="col-sm-6">
                  <input type="text" class="form-control" id="username" placeholder="請輸入用戶名" name="username">
                </div>
              </div>
               <div class="form-group">
                <label for="inputPassword3" class="col-sm-2 control-label">密碼</label>
                <div class="col-sm-6">
                  <input type="password" class="form-control" id="inputPassword3" placeholder="請輸入密碼" name="password">
                </div>
              </div>
               <div class="form-group">
                <label for="confirmpwd" class="col-sm-2 control-label">確認密碼</label>
                <div class="col-sm-6">
                  <input type="password" class="form-control" id="confirmpwd" placeholder="請輸入確認密碼">
                </div>
              </div>
              <div class="form-group">
                <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
                <div class="col-sm-6">
                  <input type="email" class="form-control" id="inputEmail3" placeholder="Email" name="email">
                </div>
              </div>
             <div class="form-group">
                <label for="usercaption" class="col-sm-2 control-label">姓名</label>
                <div class="col-sm-6">
                  <input type="text" class="form-control" id="usercaption" placeholder="請輸入姓名" name="name">
                </div>
              </div>
              <div class="form-group opt">  
              <label for="inlineRadio1" class="col-sm-2 control-label">性別</label>  
              <div class="col-sm-6">
                <label class="radio-inline">
              <input type="radio" name="sex" id="inlineRadio1" value="1"></label>
            <label class="radio-inline">
              <input type="radio" name="sex" id="inlineRadio2" value="0"></label>
            </div>
              </div>        
              <div class="form-group">
                <label for="date" class="col-sm-2 control-label">出生日期</label>
                <div class="col-sm-6">
                  <input type="date" class="form-control"  name="birthday">              
                </div>
              </div>
              
              <div class="form-group">
                <label for="date" class="col-sm-2 control-label">驗證碼</label>
                <div class="col-sm-3">
                  <input type="text" class="form-control"  >
                  
                </div>
                <div class="col-sm-2">
                <img src="${pageContext.request.contextPath}/image/captcha.jhtml"/>
                </div>
                
              </div>
             
              <div class="form-group">
                <div class="col-sm-offset-2 col-sm-10">
                  <input type="submit"  width="100" value="注冊" name="submit" border="0"
                    style="background: url('${pageContext.request.contextPath}/images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
                    height:35px;width:100px;color:white;">
                </div>
              </div>
            </form>
    </div>
    
    <div class="col-md-2"></div>
  
</div>
</div>

      
    
    <div style="margin-top:50px;">
            <img src="${pageContext.request.contextPath}/image/footer.jpg" width="100%" height="78" alt="我們的優勢" title="我們的優勢" />
        </div>

        <div style="text-align: center;margin-top: 5px;">
            <ul class="list-inline">
                <li><a>關於我們</a></li>
                <li><a>聯系我們</a></li>
                <li><a>招賢納士</a></li>
                <li><a>法律聲明</a></li>
                <li><a>友情鏈接</a></li>
                <li><a target="_blank">支付方式</a></li>
                <li><a target="_blank">配送方式</a></li>
                <li><a>服務聲明</a></li>
                <li><a>廣告聲明</a></li>
            </ul>
        </div>
        <div style="text-align: center;margin-top: 5px;margin-bottom:20px;">
            Copyright &copy; 2005-2016 傳智商城 版權所有
        </div>

</body></html>
register.jsp
c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/tb47
c3p0.user=root
c3p0.password=123456
c3p0.properties
package com.itheima.web.servlet.base;

import java.io.IOException;
import java.lang.reflect.Method;

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

/**
 * 通用的servlet
 */
public class BaseServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.獲取方法名稱
            String mName = request.getParameter("method");
            
            //1.1判斷 參數是否為空  若為空,執行默認的方法
            if(mName == null || mName.trim().length()==0){
                mName = "index";
            }
            
            //2.獲取方法對象
            Method method = this.getClass().getMethod(mName, HttpServletRequest.class,HttpServletResponse.class);
            
            //3.讓方法執行,接受返回值
            String path=(String) method.invoke(this, request,response);
            
            //4.判斷返回值是否為空 若不為空統一處理請求轉發
            if(path != null){
                request.getRequestDispatcher(path).forward(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    
    public String index(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println("親,不要搗亂");
        return null;
    }
}
BaseServlet
package com.itheima.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;

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

import org.apache.commons.beanutils.BeanUtils;

import com.itheima.constant.Constant;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.UUIDUtils;
import com.itheima.web.servlet.base.BaseServlet;
import com.sun.xml.internal.bind.v2.runtime.unmarshaller.InterningXmlVisitor;

/**
 * 用戶模塊
 */
public class UserServlet extends BaseServlet {
    private static final long serialVersionUID = 1L;

    /**
     * 退出
     */
    public String logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        
        response.sendRedirect(request.getContextPath());
        return null;
    }
    
    /**
     * 用戶登錄
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.獲取用戶名和密碼
            String username = request.getParameter("username");
            String password    = request.getParameter("password");
            
            //2.調用service完成登錄 返回值:user
            UserService us = new UserServiceImpl();
            User user=us.login(username,password);
            
            //3.判斷user 根據結果生成提示
            if(user == null){
                //用戶名和密碼不匹配
                request.setAttribute("msg", "用戶名和密碼不匹配");;
                return "/jsp/login.jsp";
            }
            
            //若用戶不為空,繼續判斷是否激活
            if(Constant.USER_IS_ACTIVE != user.getState()){
                //未激活
                request.setAttribute("msg", "請先去郵箱激活,再登錄!");
                return "/jsp/msg.jsp";
            }
            
            //登錄成功 保存用戶登錄狀態
            request.getSession().setAttribute("user", user);
            
            /////////////////記住用戶名//////////////////////
            //判斷是否勾選了記住用戶名
            if(Constant.SAVE_NAME.equals(request.getParameter("savename"))){
                Cookie c = new Cookie("saveName", URLEncoder.encode(username, "utf-8"));
                
                c.setMaxAge(Integer.MAX_VALUE);
                c.setPath(request.getContextPath()+"/");
                
                response.addCookie(c);
            }
            ///////////////////////////////////////
            
            //跳轉到 index.jsp
            response.sendRedirect(request.getContextPath());
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "用戶登錄失敗");
            return "/jsp/msg.jsp";
        }
        
        return null;
    }
    
    /**
     * 跳轉到登錄頁面
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String loginUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return "/jsp/login.jsp";
    }
    
    /**
     * 用戶激活
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //1.接受code
            String code = request.getParameter("code");
            
            //2.調用service完成激活 返回值:user
            UserService us=new UserServiceImpl();
            User user=us.active(code);
            
            //3.判斷user 生成不同的提示信息
            if(user == null){
                //沒有找到這個用戶,激活失敗
                request.setAttribute("msg", "激活失敗,請重新激活或者重新注冊~");
                return "/jsp/msg.jsp";
            }
            
            //激活成功 
            request.setAttribute("msg", "恭喜你,激活成功了,可以登錄了~");
        } catch (Exception e) {
            request.setAttribute("msg", "激活失敗,請重新激活或者重新注冊~");
            return "/jsp/msg.jsp";
        }
        return "/jsp/msg.jsp";
    }
    
    /**
     * 用戶注冊
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String regist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        try {
            //1.封裝對象
            User user = new User();
            BeanUtils.populate(user, request.getParameterMap());
            
            //1.1手動封裝uid
            user.setUid(UUIDUtils.getId());
            
            //1.2手動封裝激活狀態 state
            user.setState(Constant.USER_IS_NOT_ACTIVE);
            
            //1.3手動封裝激活碼 code
            user.setCode(UUIDUtils.getCode());
            
            //2.調用service完成注冊
            UserService us=new UserServiceImpl();
            us.regist(user);
            
            //3.頁面轉發 提示信息
            request.setAttribute("msg", "恭喜你,注冊成功,請登錄郵箱完成激活!");
        }catch (Exception e) {
            e.printStackTrace();
            //轉發到 msg.jsp
            request.setAttribute("msg", "用戶注冊失敗!");
            return "/jsp/msg.jsp";
        }
        
        return "/jsp/msg.jsp";
    }
    
    /**
     * 跳轉到注冊頁面
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    public String registUI(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        return "/jsp/register.jsp";
    }

}
UserServlet 用戶模塊
package com.itheima.web.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
 * 統一編碼
 * @author Administrator
 *
 */
public class EncodingFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub

    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1.強轉
        HttpServletRequest request=(HttpServletRequest) req;
        HttpServletResponse response=(HttpServletResponse) resp;
        
        //2.放行
        chain.doFilter(new MyRequest(request), response);
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub

    }

}
class MyRequest extends HttpServletRequestWrapper{
    private HttpServletRequest request;
    private boolean flag=true;
    
    
    public MyRequest(HttpServletRequest request) {
        super(request);
        this.request=request;
    }
    
    @Override
    public String getParameter(String name) {  
        if(name==null || name.trim().length()==0){
            return null;
        }
        String[] values = getParameterValues(name);
        if(values==null || values.length==0){
            return null;
        }
        
        return values[0];
    }
    
    @Override
    /**
     * hobby=[eat,drink]
     */
    public String[] getParameterValues(String name) {
        if(name==null || name.trim().length()==0){
            return null;
        }
        Map<String, String[]> map = getParameterMap();
        if(map==null || map.size()==0){
            return null;
        }
        
        return map.get(name);
    }
    
    @Override
    /**
     * map{ username=[tom],password=[123],hobby=[eat,drink]}
     */
    public Map<String,String[]> getParameterMap() {  
        
        /**
         * 首先判斷請求方式
         * 若為post  request.setchar...(utf-8)
         * 若為get 將map中的值遍歷編碼就可以了
         */
        String method = request.getMethod();
        if("post".equalsIgnoreCase(method)){
            try {
                request.setCharacterEncoding("utf-8");
                return request.getParameterMap();
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else if("get".equalsIgnoreCase(method)){
            Map<String,String[]> map = request.getParameterMap();
            if(flag){
                for (String key:map.keySet()) {
                    String[] arr = map.get(key);
                    //繼續遍歷數組
                    for(int i=0;i<arr.length;i++){
                        //編碼
                        try {
                            arr[i]=new String(arr[i].getBytes("iso8859-1"),"utf-8");
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
                flag=false;
            }
            //需要遍歷map 修改value的每一個數據的編碼
            
            return map;
        }
        
        return super.getParameterMap();
    }
    
}
EncodingFilter 統一編碼
package com.itheima.service.impl;

import com.itheima.constant.Constant;
import com.itheima.dao.UserDao;
import com.itheima.dao.impl.UserDaoImpl;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import com.itheima.utils.MailUtils;

public class UserServiceImpl implements UserService {

    @Override
    /**
     * 用戶注冊
     */
    public void regist(User user) throws Exception {
        //1.調用dao完成注冊
        UserDao ud=new UserDaoImpl();
        ud.save(user);
        
        //2.發送激活郵件
        String emailMsg="恭喜"+user.getName()+":成為我們商城的一員,<a href='http://localhost/store/user?method=active&code="+user.getCode()+"'>點此激活</a>";
        MailUtils.sendMail(user.getEmail(), emailMsg);
    }

    @Override
    /**
     * 用戶激活
     */
    public User active(String code) throws Exception {
        UserDao ud=new UserDaoImpl();
        //1.通過code獲取用戶
        User user=ud.getByCode(code);
        
        //1.1 通過激活碼沒有找到 用戶
        if(user == null){
            return null;
        }
        
        //2.若獲取到了 修改用戶
        user.setState(Constant.USER_IS_ACTIVE);
        user.setCode(null);
        
        ud.update(user);
        return user;
    }

    @Override
    /**
     * 用戶登錄
     */
    public User login(String username, String password) throws Exception {
        UserDao ud=new UserDaoImpl();
        
        return ud.getByUsernameAndPwd(username,password);
    }

}
UserServiceImpl
package com.itheima.dao.impl;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import com.itheima.dao.UserDao;
import com.itheima.domain.User;
import com.itheima.utils.DataSourceUtils;

public class UserDaoImpl implements UserDao{

    @Override
    /**
     * 用戶注冊
     */
    public void save(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        /*
         *  `uid` varchar(32) NOT NULL,
              `username` varchar(20) DEFAULT NULL,
              `password` varchar(20) DEFAULT NULL,
              
              `name` varchar(20) DEFAULT NULL,
              `email` varchar(30) DEFAULT NULL,
              `telephone` varchar(20) DEFAULT NULL,
              
              `birthday` date DEFAULT NULL,
              `sex` varchar(10) DEFAULT NULL,
              `state` int(11) DEFAULT NULL,
              
              `code` varchar(64) DEFAULT NULL,
         */
        String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?);";
        qr.update(sql, user.getUid(),user.getUsername(),user.getPassword(),
                user.getName(),user.getEmail(),user.getTelephone(),
                user.getBirthday(),user.getSex(),user.getState(),
                user.getCode());
    }

    @Override
    /**
     * 通過激活碼獲取用戶
     */
    public User getByCode(String code) throws Exception {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from user where code = ? limit 1";
        return qr.query(sql, new BeanHandler<>(User.class), code);
    }

    @Override
    /**
     * 更新用戶
     */
    public void update(User user) throws Exception {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        /*
         *  `uid` varchar(32) NOT NULL,
              `username` varchar(20) DEFAULT NULL,
              `password` varchar(20) DEFAULT NULL,
              
              `name` varchar(20) DEFAULT NULL,
              `email` varchar(30) DEFAULT NULL,
              `telephone` varchar(20) DEFAULT NULL,
              
              `birthday` date DEFAULT NULL,
              `sex` varchar(10) DEFAULT NULL,
              `state` int(11) DEFAULT NULL,
              
              `code` varchar(64) DEFAULT NULL,
         */
        String sql="update user set password = ?,sex = ?,state = ?,code = ? where uid = ?";
        qr.update(sql, user.getPassword(),user.getSex(),user.getState(),user.getCode(),user.getUid());
    }

    @Override
    /**
     * 用戶登錄
     */
    public User getByUsernameAndPwd(String username, String password) throws Exception {
        QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource());
        String sql = "select * from user where username = ? and password = ? limit 1";
        return qr.query(sql, new BeanHandler<>(User.class), username,password);
    }

}
UserDaoImpl
package com.itheima.domain;

public class User {
    /*
     *  `uid` varchar(32) NOT NULL,
          `username` varchar(20) DEFAULT NULL,
          `password` varchar(20) DEFAULT NULL,
          
          `name` varchar(20) DEFAULT NULL,
          `email` varchar(30) DEFAULT NULL,
          `telephone` varchar(20) DEFAULT NULL,
          
          `birthday` date DEFAULT NULL,
          `sex` varchar(10) DEFAULT NULL,
          `state` int(11) DEFAULT NULL,
          
          `code` varchar(64) DEFAULT NULL,
     */
    
    private String uid;
    private String username;
    private String password;
    
    private String name;
    private String email;
    private String telephone;
    
    private String birthday;
    private String sex;
    private Integer state;
    
    private String code;

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getState() {
        return state;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }
    
    
}
User

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM