cookie自动登录(一月内不用登录)

package com.siben.model.loginmodel.service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.siben.model.loginmodel.interfaces.ICook;

/**
* 以前用来做过自动登录
* @author Jan
*
*/
public class CookServiceImpl implements ICook {
/**
* 添加Cook
*/
@Override
public boolean addCook(HttpServletResponse res, String key, String value) {
Cookie cook = new Cookie(key, value);//新建一个Cook,是键值(key-value)关系
int month = 60 * 60 * 24 * 30;// 设置一个月(秒*分*时*天)
cook.setMaxAge(month);// 设置Cook的生存期为一个月
cook.setPath("/");//设置存诸路经
res.addCookie(cook);//将cook添加到response对象中。由response对象返回给户端
return true;
}

/**
* 获得Cook
*/
@Override
public Cookie getCook(HttpServletRequest req, String key) {
Cookie cook[] = req.getCookies();//获得客户端的请求resquest对象中的cook数组对象
if (cook==null)//判断cook是否为空
return null;
for (Object obj : cook) {//for循环得到相应的cookie
Cookie ck = (Cookie) obj;
if (ck.getName().equals(key)) {
return ck;
}
}
return null;
}

}

你可能感兴趣的:(Java)