`
dou_shini8820
  • 浏览: 77829 次
社区版块
存档分类
最新评论

使用cookie记住用户名和密码

 
阅读更多
//1、登陆页jsp页面最上方使用java代码取得cookie'中的用户名和密码

 

String name="";
String password="";
try{
	Cookie[] cookies=request.getCookies();
	if(cookies!=null){
		for(int i=0;i<cookies.length;i++){
			if("cookie_user".equals(cookies[i].getName())){
				String v=cookies[i].getValue();
				if(v!=null&&!"".equals(v)){
					String[] vs = v.split("-");
					name=vs[0];
					if(vs[1]!=null&&!"null".equals(vs[1])){
						password=vs[1];
					}
				}
			}
			request.setAttribute("name",name);
			request.setAttribute("password",password);
		}
	}
}catch(Exception e){
	e.printStackTrace();
}

 

 

//2、在jsp页面

 

 

<tr>
					<td width="78" rowspan="2" valign="top">
						<img id="divTabImg" src="${pageContext.request.contextPath}/images/head/loginHead001.png" />
					</td>
					<td colspan="2">
						<div id="divTabLoginFrm">
							<div style="clear:both;">
								<div id="divTabAccFont">代理人</div>
								<div id="divTabAccInput"><input type="text" style="margin-left:0px;" name="userName" id="userName" tabindex=1 value="<%=name%>" onkeydown="if(event.keyCode==13)event.keyCode=9"/></div>
							</div>
							<div style="clear:both;">
								<div id="divTabPwdFont">密码</div>
								<div id="divTabPwdInput"><input type="password"  style="margin-left:0px;" name="password" id="password" tabindex=2 value="<%=password%>" onkeydown="if(event.keyCode==13)document.getElementById('loginBtn').click()"/></div>
							</div>
						</div>
					</td>
				</tr>
				<tr>
				  <td width="24">
				  		<input name="flag" id="flag" type="checkbox" <%if(!(flag!=null && flag.equals("1"))){%>  value ="0"; <%}else {%> checked ;value="1" <%;}%> tabindex=3 onclick="remmberMe(this)"/>
				  		<input id="hiddenCheck" type="hidden"/>
				  </td>
					<td width="258">记住密码</td>
				</tr>

 

 

//3、触发登陆按纽的js方法判断是否需要记住密码

 

function login(obj){
	var f=$("#flag").attr("checked");
	if(f==true){
		$("#flag").attr("value",1);
	}
}

 

 

 

//4、java代码中创建cookie
String flag=request.getParameter("flag");
						//设置cookie
						if(flag!=null&&"1".equals(flag)){
							Cookie cookie=new Cookie("cookie_user",username+"-"+this.requestString("password"));
							cookie.setMaxAge(60*60*24*30);
							response.addCookie(cookie);
						}else{
							Cookie cookie=new Cookie("cookie_user",username+"-"+null);
							cookie.setMaxAge(60*60*24*30);
							response.addCookie(cookie);
						}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics