qileilove

blog已经转移至github,大家请访问 http://qaseven.github.io/

Java web项目用cookie记住用户名、密码

 web 项目中一般在登录的时候都会用到记住密码功能。
  1.jsp页面:
<% 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("name",name);
request.setAttribute("passward",password);
}
}
}catch(Exception e){
e.printStackTrace();
}
%>
<body>
<div id="logo"><img src="<%=request.getContextPath() %>/frontsite/Images/Logo.jpg" width="244" height="44" alt="" /></div>
<div id="loginfrm">
<form action="<%=request.getContextPath() %>/frontsite/login.do?method=login" method="post" id="forms" onsubmit="checkForm();return false;">
<div class="frm">
<ul>
<li class="l1">用户名:</li>
<li class="l2"><input name="login_id" type="text" id="login_id" class="input" value="<%=name %>"/></li>
<li class="l3">* 最大限度为20字节</li>
<li class="l1">密码:</li>
<li class="l2"><input name="login_pwd" type="password" id="login_pwd" class="input" value="<%=password %>"/></li>
<li class="l3">* 最大限度为20字节</li>
<li class="l1">验证码:
<li class="l2" style="width: 180px;"><input name="checkImg" id="checkImg" type="text" class="input" style="width: 60px;" size="10" />
&nbsp;&nbsp;<img src="<%=request.getContextPath() %>/CheckImg_FT" width="49" height="22" /></li>
<li class="l4">
<label><input type="checkbox" name="flag" id="flag" value="1" <%if(flag!=null && flag.equals("1")){%> checked ; value ="1"; <%}else {%> value="0" <%;}%> />记住密码</label>
<label><span style="margin-left:10px; color: #F00;" ><html:errors /></span></label>
</li>
<li class="l4"><input type="image" name="imageField" id="imageField" src="<%=request.getContextPath() %>/frontsite/Images/login_bnt.jpg" /></li>
</ul>
</div>
</form>
</div>
</body>


  2.java 类:
String flag = request.getParameter("flag");
//set cookie
if(flag!=null && flag.equals("1")){
Cookie cookie = new Cookie("cookie_user", po.getLogin_id()+"-"+form.getLogin_pwd());
cookie.setMaxAge(60*60*24*30); //cookie 保存30天
response.addCookie(cookie);
}else{
Cookie cookie = new Cookie("cookie_user",po.getLogin_id()+"-"+null);
cookie.setMaxAge(60*60*24*30); //cookie 保存30天
response.addCookie(cookie);
}

posted on 2013-11-12 11:02 顺其自然EVO 阅读(2285) 评论(0)  编辑  收藏 所属分类: android


只有注册用户登录后才能发表评论。


网站导航:
 
<2013年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

常用链接

留言簿(55)

随笔分类

随笔档案

文章分类

文章档案

搜索

最新评论

阅读排行榜

评论排行榜