jsp利用cookie記住用戶名,下次登錄時顯示在文本框中(僅僅一個Cookie就整了將近三個小時,⊙﹏⊙b汗)


<%@page import="java.net.URLDecoder"%>
<%@page import="sun.security.util.Length"%>
<%@ 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 cardid = null ;
Cookie[] cks = request.getCookies() ;

if(cks != null)
{ 
     // 如果已經設置了cookie , 則得到它的值,將該值放在卡號文本框的value中
        for(int i=0; i<cks.length; i++)
        {
               if(cks[i].getName().equals("cardid"))

            cardid = cks[i].getValue();
        }
     }
%>
<form action="Cookie2.jsp" method="post">
卡號<input type="text" name="cardid" value="<% if(cardid != null) out.println(cardid); %>"><br>
密碼<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>

</body>
</html>
<%@page import="java.net.URLEncoder"%>
<%@page import="com.shuyinghengxie.bank.CardDAO"%>
<%@ 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 kahao = request.getParameter("cardid") ;

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

if(kahao==null || password==null ||
        kahao == "" || password == "" )
{
    out.write("請正確登錄") ;
}
else
{
    CardDAO cd = new CardDAO() ;
    
    if(cd.checkLogin(kahao, password))
    {
        //out.write("登陸成功") ;
        response.getWriter().write("驗證通過") ;
        
        //創建Cookie
        Cookie ck = new Cookie("cardid",kahao) ;
        
        //設置過期時間
        ck.setMaxAge(10*24*60*60)  ;
        
        //發送
        response.addCookie(ck) ;
        
        response.sendRedirect("a.jsp") ;
        
    }
    else
    {
        out.write("登錄失敗") ;
    }
}
%>
</body>
</html>
<%@page import="java.net.URLDecoder"%>
<%@ 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>
登陸成功!
</body>
</html>

這時候點擊返回,發現文本框中存在剛剛登陸過的賬號,即使刷新依然存在

 


免責聲明!

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



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