package com.gamecenter.api.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import com.gamecenter.api.common.UserInfo; /**
* 类说明
* @author chitu
* @version 创建时间:2016年11月21日 下午1:39:51
*/
public class CookieUtil {
//保存cookie时的cookieName
private final static String cookieDomainName = "gamecenter";
//加密cookie时的网站自定码
private final static String webKey = "gamecenter";
//设置cookie有效期是两个星期,根据需要自定义
private final static long cookieMaxAge = 60 * 60 * 24 * 7 * 2;
//保存Cookie到客户端-------------------------------------------------------------------------
//在CheckLogonServlet.java中被调用
//传递进来的user对象中封装了在登陆时填写的用户名与密码 public static void saveCookie(String username,String password, HttpServletResponse response) throws Exception {
//cookie的有效期
long validTime = System.currentTimeMillis() + (cookieMaxAge * 5000);
//MD5加密用户详细信息
String cookieValueWithMd5 =getMD5(username + ":" + password+ ":" + validTime + ":" + webKey);
//将要被保存的完整的Cookie值
String cookieValue = username + ":" + validTime + ":" + cookieValueWithMd5;
//再一次对Cookie的值进行BASE64编码
String cookieValueBase64 = new String(Base64Util.encode(cookieValue.getBytes()));
//开始保存Cookie
Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
//存两年(这个值应该大于或等于validTime)
cookie.setMaxAge(60 * 60 * 24 * 365 * 2);
//cookie有效路径是网站根目录
cookie.setPath("/");
//向客户端写入
response.addCookie(cookie);
} //读取Cookie,自动完成登陆操作----------------------------------------------------------------
//在Filter程序中调用该方法,见AutoLogonFilter.java
public static void readCookieAndLogon(HttpServletRequest request, HttpServletResponse response,FilterChain chain) throws IOException, ServletException,UnsupportedEncodingException{
//根据cookieName取cookieValue
Cookie cookies[] = request.getCookies();
String cookieValue = null;
if(cookies!=null){
for(int i = 0; i < cookies.length; i++){
if (cookieDomainName.equals(cookies[i].getName())) {
cookieValue = cookies[i].getValue();
break;
}
}
}
//如果cookieValue为空,返回,
if(cookieValue==null){
return;
}
//如果cookieValue不为空,才执行下面的代码
//先得到的CookieValue进行Base64解码
String cookieValueAfterDecode = new String (Base64Util.decode(cookieValue),"utf-8");
//对解码后的值进行分拆,得到一个数组,如果数组长度不为3,就是非法登陆
String cookieValues[] = cookieValueAfterDecode.split(":");
if(cookieValues.length!=3){
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("你正在用非正常方式进入本站...");
out.close();
return;
}
//判断是否在有效期内,过期就删除Cookie
long validTimeInCookie = new Long(cookieValues[1]);
if(validTimeInCookie < System.currentTimeMillis()){
//删除Cookie
clearCookie(response);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("你的Cookie已经失效,请重新登陆");
out.close();
return;
}
//取出cookie中的用户名,并到数据库中检查这个用户名,
String username = cookieValues[0];
//根据用户名到数据库中检查用户是否存在
UserDAO ud = DaoImplFactory.getInstance();
User user = ud.selectUserByUsername(username);
//如果user返回不为空,就取出密码,使用用户名+密码+有效时间+ webSiteKey进行MD5加密
if(user!=null){
String md5ValueInCookie = cookieValues[2];
String md5ValueFromUser =getMD5(user.getUserName() + ":" + user.getPassword()
+ ":" + validTimeInCookie + ":" + webKey);
//将结果与Cookie中的MD5码相比较,如果相同,写入Session,自动登陆成功,并继续用户请求
if(md5ValueFromUser.equals(md5ValueInCookie)){
HttpSession session = request.getSession(true);
session.setAttribute("user", user);
chain.doFilter(request, response);
}
}else{
//返回为空执行
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println("cookie验证错误!");
out.close();
return; } } //用户注销时,清除Cookie,在需要时可随时调用-----------------------------------------------------
public static void clearCookie( HttpServletResponse response){
Cookie cookie = new Cookie(cookieDomainName, null);
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
} //获取Cookie组合字符串的MD5码的字符串----------------------------------------------------------------
public static String getMD5(String value) {
String result = null;
try{
byte[] valueByte = value.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(valueByte);
result = toHex(md.digest());
} catch (NoSuchAlgorithmException e){
e.printStackTrace();
}
return result;
}
//将传递进来的字节数组转换成十六进制的字符串形式并返回
private static String toHex(byte[] buffer){
StringBuffer sb = new StringBuffer(buffer.length * 2);
for (int i = 0; i < buffer.length; i++){
sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
}
return sb.toString();
}
}

  

Java:Cookie实现记住用户名、密码的更多相关文章

  1. Jquery 实现 “下次自动登录” 记住用户名密码功能

    转载自:http://blog.csdn.net/aspnet_lyc/article/details/12030039?utm_source=tuicool&utm_medium=refer ...

  2. jQuery cookie 实现记住用户名和密码功能

    jQuery cookie 实现记住用户名和密码功能 HTML代码 <div class="wrap"> <div class="line-top&qu ...

  3. cookie记住用户名密码

    <script src="js/jquery.cookie.js" type="text/javascript"></script> $ ...

  4. PLSQL自动登录,记住用户名密码

    转: PLSQL自动登录,记住用户名密码&日常使用技巧 配置启动时的登录用户名和密码 这是个有争议的功能,因为记住密码会给带来数据安全的问题. 但假如是开发用的库,密码甚至可以和用户名相同,每 ...

  5. SharedPreferences实现自动登录记住用户名密码

    最近Android项目需要一个自动登录功能,完成之后,特总结一下,此功能依靠SharedPreferences进行实现.   SharedPreferences简介 SharedPreferences ...

  6. Windows下让Git记住用户名密码(https)

    最近开始跟老板共同维护公司的框架代码,于是毫不犹豫地选择了Git这个驰名的版本控制系统(公司使用的是TFS,但外网访问老是断线). 选择的托管平台是OSChina,原因是其可以新建私有项目. 在拉取和 ...

  7. TortoiseGit自动记住用户名密码的方法

    TortoiseGit自动记住用户名密码的方法 windows下比较比较好用的git客户端有2种: msysgit + TortoiseGit(乌龟git) GitHub for Windows gi ...

  8. 用cookie实现记住用户名和密码

    1.当第一次发送请求时,在jsp页面并不能获取cookie对象,第一次是addCookie,之后再请求时才能获得. session和sessionid在服务器端生成的时候,同时把sessionID放在 ...

  9. cookie 实现记住用户名演示 通过代码迅速理解cookie

    // 登录页 可直接 tomcat部署 测试 1 package com.itheima.login; import java.io.IOException; import java.io.Print ...

随机推荐

  1. 166. Fraction to Recurring Decimal (Math)

    Given two integers representing the numerator and denominator of a fraction, return the fraction in ...

  2. Hands-On Unity 2018 x 移动游戏开发教程

    Hands-On Unity 2018 x Game Development for Mobile 使用Unity 2018.2创建具有出色游戏功能的精彩游戏   想学习在Unity制作游戏,但不知道 ...

  3. GCD - Extreme (II) (欧拉函数妙用)

    https://cn.vjudge.net/problem/UVA-11426 题意:求 解题思路:我们可以定义一个变量dis[n],dis[n]意为1~(n-1)与n的gcd(最大公约数)的总和,那 ...

  4. js学习(4) 函数

    JavaScript有三种声明函数的方法 (1)function命令 function print(s) { console.log(s); } (2)函数表达式 1.var print = func ...

  5. cmp指令

    cmp是比较指令,cmp的功能相当于减法指令,只是不保存结果.cmp指令执行后,将对标志寄存器产生影响.其他相关指令通过识别这些被影响的标志寄存器位来得知比较结果. cmp指令格式: cmp 操作对象 ...

  6. Android开发日常-listview滚动方法梳理

    listview滚动方法梳理 1.setSelection(position); 滚动到指定条目 2.setSelectionFromTop(position,y): 距离指定条目向下偏移y(像素) ...

  7. Chapter3_操作符_别名机制

    Java中的别名机制实际体现的是对于“=”这一类赋值操作符的使用规则和内涵.“=”的实际内涵是指将右边的变量的值(对于基本数据类型而言)或者某一个对象的引用(对于某个具体对象而言)复制到左边的变量名所 ...

  8. JDK源码核心包

    一.核心包有哪些? Jdk的包中,除开了lang包下面的类,用得最多的应该要属于util包下面的类了, 本篇文章主要针对Jdk的util包下面的类(util目录下面的类,暂时不包括util 包下面的子 ...

  9. CSS样式总结(作业六)

    1:CSS基本介绍 CSS全称为“层叠样式表 (Cascading Style Sheets)”,它主要是用于定义HTML内容在浏览器内的显示样式,如文字大小.颜色.字体加粗等. css 样式由选择符 ...

  10. div辅助线【完整版】

    ## <html> <head> <link rel="stylesheet" type="https://cdn.bootcss.com/ ...