您的位置:首页 > 其它

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

2017-06-02 22:03 381 查看
开发过程中,有时候遇到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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: