首页 > 学院 > 开发设计 > 正文

java 中 Cookie的用法

2019-11-17 04:00:15
字体:
来源:转载
供稿:网友
Cookie:记录用户登陆状态,可以在客户端创建cookie,可以使用户第二次登陆的时候不用输入用户名和密码,即可以登陆到主页


主要代码:  


LoginView 中: (获取cookie)

//获取cookie

Cookie [] cs=request.getCookies();

String name="";

String value="";

if(null!=cs)

{   

   System.out.PRintln("cs.length:"+cs.length);

   for(int i=0;i<cs.length;i++)

   {

      Cookie c=cs[i];

      name=c.getName();

      value=c.getValue();

   }

}

if(null!=cs&&!(name.trim().equals("JsessionID")))

{

   request.setAttribute("username",name);

   request.setAttribute("userpass",value);

   request.getRequestDispatcher("/servlet/Controller1").forward(request,response);

}



Controller 控制器中:(创建cookie)

if(sflag)   // if 登陆成功(sflag表示,验证用户成功)

{

if(usercheckbox==null)

{

//System.out.println("您没有选中!!!");   //没有选中,无操作

}

else

{

//System.out.println("您以选中!");    // 如果选中,则创建cookie

//创建cookie

Cookie cookie=new Cookie(username,userpass);

//设置cookie的时效

cookie.setMaxAge(60*60*24*7*2);

//设置cookie 的使用路径

cookie.setPath("/");

//发送cookie

response.addCookie(cookie);

}

HttpSession session=request.getSession();

session.setAttribute("userinfo",username); //绑定用户名

response.sendRedirect("/hygj0331/servlet/Controller3");

             //发送到控制器Controller3,用来查询所有的数据,用来展示数据

}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表