cookie自动登录java_JavaWeb学习笔记<1>cookie实现自动登录

1.在登录表单中输入账户密码

用户名: 

密码: 

记住我

2.在test.jsp里面验证用户名以及密码,第一次登录时添加一个cookie

//获得用户名和密码

String name = request.getParameter("name");

String password = request.getParameter("password");

//判断是否点了记住我,点击了则为on,否则为null

String checked = request.getParameter("check");

if(checked != null){

//下面继续执行,否则不新建cookie

}

//创建新的cookie

Cookie cookie = new Cookie("userName", name);

Cookie cook = new Cookie("password",password);

//设置保存时间,注意放在添加的前面

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

cook.setMaxAge(7*24*60*60);

//添加

response.addCookie(cookie);

response.addCookie(cook);

%>

3.现在已经有了cookie,则需要在login.jsp中进行验证,如果存在,自动登录或者直接对name和password赋值

//定义两个变量用来接收cookie中的value

String name = null;

String password = null;

//获得cookie

Cookie [] cookies = request.getCookies();

if(cookies != null){

//进行遍历循环

for(Cookie cookie:cookies){

//如果存在,对name赋值

if("userName".equals(cookie.getName())){

name = cookie.getValue();

}

//如果存在,对password赋值

if("password".equals(cookie.getName())){

password = cookie.getValue();

}

}

//判断,如果不为空,则证明存在,直接给name和password赋值,下次访问会自动记住

if(name != null&&password != null){

request.setAttribute("name", name);

request.setAttribute("password", password);

}

//也可以直接跳转

if(name != null&&password != null){

response.sendRedirect(“main.jsp”);

}

}

%>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值