日期:2014-05-18  浏览次数:20718 次

jsp实现cookie自动登录怎么做?
当用户登录网站时候有是否自动登录选项
当选择了之后,
下次要自动登录.



------解决方案--------------------
部分代码如下:
login.java中
...
Cookie usercookie=new Cookie( "usercookie ",user.getUsername());
usercookie.setMaxAge(24*60*60);
usercookie.setPath( "/koubeiTest/ ");
usercookie.setDomain( "www.lifeng.com ");
ServletActionContext.getResponse().addCookie(usercookie);
...

login.jsp中
<%
Cookie[] cookie = request.getCookies();
if(cookie!=null){
for(int i = 0; i < cookie.length; i++){
Cookie myCookie = cookie[i];
if(myCookie.getName().equals( "usercookie ")){
response.sendRedirect( "跳转到某用户的界面 ");
}}}%>

我的疑问是

------解决方案--------------------
js
function ckForm(){
var sname =document.loginForm.Login.value;
var snpwd =document.loginForm.Pwd.value;
var snexa =document.loginForm.examine.value;

if(sname== " "){
sname=null;
}
if(snpwd== " "){
snpwd=null;
}
if(snexa== " "){
snexa=null;
}
if(sname==null){
alert( 'please input name ');
return false;

}else if(snpwd==null){
alert( 'please input pwd ');
return false;
}else if(snexa==null){
alert( 'please input examine ')
return false;
}
else{

}
}


function getCookieVal(offset)
{
var iEndStr=document.cookie.indexOf( "; ",offset);
if(iEndStr==-1) iEndStr=document.cookie.length;
return unescape(document.cookie.substring(offset,iEndStr));
}

function getCookie(name)
{
var strArg=name+ "= ";
var iArgLength=strArg.length;
var iCookieLength=document.cookie.length;
var iIndex=0;
while(iIndex <iCookieLength)
{
var kIndex=iIndex+iArgLength;
if(document.cookie.substring(iIndex,kIndex)==strArg)
return getCookieVal(kIndex);

iIndex=document.cookie.indexOf( " ",iIndex)+1;

if(iIndex==0)
break;
}
return null;
}

function setCookie(name,value)
{
var strArgValue=setCookie.arguments;
var iArgLength=setCookie.arguments.length;
var expires=(2 <iArgLength)?strArgValue[2]:null;
var path=(3 <iArgLength)?strArgValue[3]:null;
var domain=(4 <iArgLength)?strArgValue[4]:null;
var secure=(5 <iArgLength)?strArgValue[5]:false;
document.cookie=name+ "= "+escape(value)+((expires==null)? " ":( ";expires= "+expires.toGMTString()))+
((path==null)? " ":( ";path= "+path))+((domain==null)? " ":( ";domain= "+domain))+
((secure==true)? ";secure ": " ");
}

------解决方案--------------------
思路:
打上“自动登陆 " 写入Cookie
下次打开网页,先读出Cookie
用读出的Cookie验证
------解决方案--------------------
用cookie是正道,自己动手丰衣足食