頁面說明:1、index.jsp登錄表單頁面 2、go.jsp表單驗證頁面 3、success.jsp登錄成功界面
1、index.jsp登錄表單頁面
1)登錄表單

1 <form action="go.jsp" name="Myfeg" onsubmit="return checkReg()" method="get"> 2 <table cellpadding="10"> 3 <tr> 4 <td> 用戶名:</td> 5 <td><input type="text" name="userName" placeholder="用戶名為4-16個字符" value="<%=userName%>"/></td> 6 </tr> 7 <tr> 8 <td> 密 碼:</td> 9 <td> <input type="password" name="userPwd" placeholder="密碼由數字字符6~18位"></td> 10 </tr> 11 <tr> 12 <td> 13 14 </td> 15 16 <td> 17 <input class="dl" type="submit" name="dl" value="登錄" style="margin-left: 10px;border:none"> 18 <input class="cz" type="button" name="cz" value="注冊" style="margin-left: 40px;border:none"> 19 </td> 20 </tr> 21 </table> 22 </form>
2)獲取cookie

1 <%-- 獲取網頁的cookie,判斷是否有需要的登錄名信息,有則顯示在用戶名框內--%> 2 <% 3 String userName = ""; 4 Cookie[] cookie = request.getCookies(); 5 if(cookie == null || cookie.length == 0){ 6 }else { 7 for (Cookie cookie1 : cookie) { 8 if (cookie1.getName().equals("userName")){ 9 userName = cookie1.getValue(); 10 //out.print(userName); 11 } 12 //out.print(cookie1.getName()+"--"); 13 } 14 } 15 %>
3)獲取地址欄參數值以及記錄訪問次數

1 <%-- 獲取地址欄的屬性值以及application記錄頁面訪問次數--%> 2 <% 3 String mess = request.getParameter("info"); 4 if (mess != null ){ 5 out.print(mess); 6 } 7 Object count = application.getAttribute("count"); 8 if(count == null){ 9 //application中未存放count 10 application.setAttribute("count", 1); 11 }else{ 12 //application中已經存放count 13 Integer i=(Integer)count; 14 application.setAttribute("count", i+1); 15 } 16 Integer icount=(Integer)application.getAttribute("count"); 17 out.println("頁面被訪問了"+icount+"次"); 18 %>
4)修改地址,刪除參數

1 <%-- 登錄失敗后,返回主頁面,修改地址欄參數,刷新之后不會顯示登錄失敗提示--%> 2 <script> 3 var url = document.URL; 4 var num = url.indexOf('?'); 5 if (num){ 6 URL = url.substring(0,num); //截取網址信息 7 history.pushState(null,null,URL); //將網址設置 8 } 9 </script>
2、go.jsp表單驗證頁面

1 <% 2 String userName = request.getParameter("userName"); 3 String userPwd = request.getParameter("userPwd"); 4 if (userName.equals("系統管理員") && userPwd.equals("123")){ 5 //登錄成功,session保存客戶信息,並創建cookie發送客戶,用於記錄登錄名,並顯示在登錄名框內 6 session.setAttribute("userName",userName); 7 Cookie cookie = new Cookie("userName",userName); 8 cookie.setPath("/"); 9 response.addCookie(cookie); 10 request.getRequestDispatcher("success.jsp").forward(request,response); 11 }else{ 12 //登錄失敗,使用重定向回到登錄界面,為地址欄添加一個屬性,提示登錄失敗 13 String info = "登錄失敗!"; 14 info = URLEncoder.encode(info,"utf-8"); 15 response.sendRedirect("index.jsp?info="+info); 16 //request.getRequestDispatcher("index.jsp").forward(request,response); 17 } 18 %>
3、success.jsp登錄成功界面

1 <% 2 String userName = (String) session.getAttribute("userName"); 3 if(userName == null || userName == ""){ 4 response.sendRedirect("index.jsp"); 5 }else {%> 6 <h1>登錄成功!歡迎您,<%out.print(session.getAttribute("userName"));%></h1> 7 <%}%> 8 <button type="button" onclick="javascript:location.href='index.jsp'">注銷</button>