浅谈利用Cookie技术实现3天免登陆

开发过程中,有时候遇到3天或者7天免登陆的业务需求,考虑使用Cookie来实现。

业务逻辑:登陆成功时将登陆名和登录密码写入到Cookie.下次登陆的时候首先去从Cookie中找到登陆名登录密码,找到了再进行匹配;如果Cookie中不含有登陆名登录密码,说明未登录,需要登录。

Servlet代码如下:

private void dologin(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username==null || password==null){
Cookie[] cookie = request.getCookies();
for (Cookie c : cookie) {
if(c.getName().equals("username")) {
username = c.getValue();
}else if(c.getName().equals("password")){
password = c.getValue();
}
}
}

if(username==null || password==null) {
request.getRequestDispatcher("login.jsp").forward(request, response);
} else {
for (User user : list) {
if(user.getUsername().equals(username) && user.getPassword().equals(password)) {
Cookie cookie1 = new Cookie("username", username);
Cookie cookie2 = new Cookie("password", password);
cookie1.setMaxAge(15);
cookie2.setMaxAge(15);
response.addCookie(cookie1);
response.addCookie(cookie2);
request.getRequestDispatcher("success.jsp").forward(request, response);
} else{
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}

}
 

代码分析:

通过request.getCookies();可以得到cookie,返回的是一个数组,遍历数据。

Cookie cookie2 = new Cookie("password", password);设置cookie,键值对的形式 response.addCookie(cookie2),将cookie添加到response请求头中。

cookie2.setMaxAge(15);设置cookie的存活时间,单位是秒,3天=60*60*24*3


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值