1. 程式人生 > >java web登入頁面上記住密碼

java web登入頁面上記住密碼

利用cookie程式設計

     login.jsp 頁面上的java程式碼:

<% String flag = (String)session.getAttribute("flag")==null?"":(String)session.getAttribute("flag");
 
String name = "";
String password = "";
try{ 
    Cookie[] cookies=request.getCookies(); 
    if(cookies!=null){ 
    for(int i=0;i<cookies.length;i++){ 
        if(cookies[i].getName().equals("cookie_user")){ 
        String value =  cookies[i].getValue();
        if(value!=null&&!"".equals(value)){
            name=cookies[i].getValue().split("-")[0]; 
            if(cookies[i].getValue().split("-")[1]!=null && !cookies[i].getValue().split("-")[1].equals("null")){
                password=cookies[i].getValue().split("-")[1]; 
            }
                     
           }
           } 
       request.setAttribute("loginName",name); 
       request.setAttribute("passwd",password); 
   } 
   } 
}catch(Exception e){ 
   e.printStackTrace(); 
} 
%> 

login.jsp頁面上的html程式碼:

		<tr>
			<td>使用者名稱:</td>
			<td>
				<input type="text" id="loginName" name="loginName" <%if(flag!=null && flag.equals("1")){%>  value ="<%=name%>"; <%}else {%> value="" <%;}%> required  style="width:180px; line-height:24px; height:24px;" />
			</td>
		</tr>
		<tr>
			<td>密 碼:</td>
			<td>
				<input type="password" id="passwd" name="passwd" <%if(flag!=null && flag.equals("1")){%>  value ="<%=password%>"; <%}else {%> value="" <%;}%> required   required style="width:180px; line-height:24px; height:24px;"/>
			</td>
		</tr>
		<tr>
			<td>驗證碼:</td>
			<td><input type="text" id="kaptcha" name="kaptcha" style="width:80px; line-height:24px; height:24px;"/>
                <span class="verification">
				<img src="images/verification.jpg" id="kaptchaImage" name="photoimg"  alt="驗證碼" title="點選換圖片"  onclick="changeImage();"/>
				<a class="refresh" href="javascript:changeImage();"></a>
		  		</span>
			</td>
		</tr>
		 <tr>
			<td colspan="2"><input type="checkbox" name="flag" id="flag" value="1" <%if(flag!=null && flag.equals("1")){%> checked ; value ="1"; <%}else {%> value="0" <%;}%> />記住密碼</td>
		</tr>

login.java類中的login.do方法中增加如下程式碼:
    //set cookie
        	if(flag!=null && flag.equals("1")){
        	    Cookie cookie = new Cookie("cookie_user", secPrivilegeUser.getLoginName()+"-"+this.passwd);                
        	    cookie.setMaxAge(60*60*24*30); //cookie 儲存30天
        	    this.getResponse().addCookie(cookie);
        	}else{  
        	    Cookie cookie = new Cookie("cookie_user",secPrivilegeUser.getLoginName()+"-"+null);                
        	    cookie.setMaxAge(60*60*24*30); //cookie 儲存30天
        	    this.getResponse().addCookie(cookie);             
        	}
        	this.getRequest().getSession().setAttribute("flag", flag);
            
  private String							   flag;
	public String getFlag() {
		return flag;
	}

	public void setFlag(String flag) {
		this.flag = flag;
	}