使用cookie記錄登陸名,下次登陸時可以記得上次的登陸名,使用cookie模擬購物車功能,使用session記住登陸信息並驗證是否登陸,防止利用url打開網站,並實現退出登陸功能html
<%@ 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> <% //提取checkTaobao.jsp中,cookie保存的淘寶名 Cookie[] cookies=request.getCookies(); String taobaoname=""; if(cookies!=null) { //遍歷 for(Cookie c: cookies) { if(c.getName().equals("taobaoname")) { taobaoname=c.getValue(); } } } %> <form action="CheckTaobao.jsp" method="post"> 用戶名:<input type="text" name="taobaoname" value="<%=taobaoname%>"><br> 密碼:<input type="password" name="taobaopassword"><br> <input type="submit" value="登錄淘寶"><br> </form> <br> <br> </body> </html>
<%@ 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> <% String taobaoname=request.getParameter("taobaoname"); String taobaopassword=request.getParameter("taobaopassword"); if(taobaoname==null||taobaopassword==null ||taobaoname.equals("")||taobaopassword.equals("")) { out.print("請輸入正確的用戶名密碼"); response.setHeader("refresh", "3;URL=LoginTaobao.jsp"); } else { //連數據庫 //驗證 if(taobaoname.equals("1234")&&taobaopassword.equals("123456")) { //用cookie記住淘寶名 Cookie cid=new Cookie("taobaoname",taobaoname); cid.setMaxAge(60*60); response.addCookie(cid); //保持登陸狀態 session.setAttribute("taobaoname",taobaoname);//session是存瀏覽器的 response.sendRedirect("MainTaobao.jsp"); } else { out.write("用戶名密碼錯誤"); response.setHeader("refresh", "3;URL=LoginTaobao.jsp"); } } %> </body> </html>
<%@ 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> 淘寶首頁 <% Object obj=session.getAttribute("taobaoname"); if(obj==null) { out.write("會話超時或未登陸,請從新輸入"); response.setHeader("refresh","6;URL=LoginTaobao.jsp"); } else { out.write(obj+",歡迎登陸!"); %> <br> <br> <a href="LogoutTaobao.jsp">退出登陸</a> <% }%> </body> </html>
<%@ 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> 銷燬session <% session.invalidate(); out.write("退出成功"); response.setHeader("refresh","3;URL=LoginTaobao.jsp"); %> </body> </html>