免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2134 | 回复: 0
打印 上一主题 下一主题

Cookie实现记住用户名、密码 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-05-26 14:20 |只看该作者 |倒序浏览
今天做一个项目就是有一个记住用户名的,选中复选框则记住用户名和密码,下次登录的时候就方便用户名的登陆:
  1. package com.laizhi.util;
  2. 002

  3. 003
  4. import java.io.IOException;
  5. 004

  6. 005
  7. import java.io.PrintWriter;
  8. 006

  9. 007
  10. import java.io.UnsupportedEncodingException;
  11. 008

  12. 009
  13. import javax.servlet.FilterChain;
  14. 010

  15. 011
  16. import javax.servlet.ServletException;
  17. 012

  18. 013
  19. import javax.servlet.http.Cookie;
  20. 014

  21. 015
  22. import javax.servlet.http.HttpServletRequest;
  23. 016

  24. 017
  25. import javax.servlet.http.HttpServletResponse;
  26. 018

  27. 019
  28. import javax.servlet.http.HttpSession;
  29. 020

  30. 021
  31. import java.security.MessageDigest;
  32. 022

  33. 023
  34. import java.security.NoSuchAlgorithmException;
  35. 024

  36. 025
  37. import com.laizhi.bean.User;
  38. 026

  39. 027
  40. import com.laizhi.dao.UserDAO;
  41. 028

  42. 029
  43. import com.laizhi.factory.DaoImplFactory;
  44. 030

  45. 031
  46. import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
  47. 032

  48. 033
  49. /*
  50. 034

  51. 035
  52. * 2014.07.01
  53. 036

  54. 037
  55. * */
  56. 038

  57. 039
  58. public class CookieUtil {
  59. 040
  60.        //保存cookie时的cookieName
  61. 041
  62.        private final static String cookieDomainName = “laizhi”;
  63. 042
  64.        //加密cookie时的网站自定码
  65. 043

  66. 044
  67.        private final static String webKey = “123456”;
  68. 045
  69.        //设置cookie有效期是两个星期,根据需要自定义
  70. 046
  71.        private final static long cookieMaxAge = 60 * 60 * 24 * 7 * 2;
  72. 047
  73.        //保存Cookie到客户端-------------------------------------------------------------------------
  74. 048
  75.        //在CheckLogonServlet.java中被调用
  76. 049
  77.        //传递进来的user对象中封装了在登陆时填写的用户名与密码
  78. 050

  79. 051
  80.        public static void saveCookie(User user, HttpServletResponse response) {
  81. 052
  82.               //cookie的有效期
  83. 053
  84.               long validTime = System.currentTimeMillis() + (cookieMaxAge * 5000);
  85. 054
  86.               //MD5加密用户详细信息
  87. 055
  88.               String cookieValueWithMd5 =getMD5(user.getUserName() + ":" + user.getPassword()
  89. 056

  90. 057
  91.                             + ":" + validTime + ":" + webKey);
  92. 058
  93.               //将要被保存的完整的Cookie值
  94. 059
  95.               String cookieValue = user.getUserName() + ":" + validTime + ":" + cookieValueWithMd5;
  96. 060
  97.               //再一次对Cookie的值进行BASE64编码
  98. 061

  99. 062
  100.               String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes()));
  101. 063
  102.               //开始保存Cookie
  103. 064
  104.               Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
  105. 065
  106.               //存两年(这个值应该大于或等于validTime)
  107. 066
  108.               cookie.setMaxAge(60 * 60 * 24 * 365 * 2);
  109. 067

  110. 068
  111.               //cookie有效路径是网站根目录
  112. 069

  113. 070
  114.               cookie.setPath("/");
  115. 071

  116. 072
  117.               //向客户端写入
  118. 073

  119. 074
  120.               response.addCookie(cookie);
  121. 075

  122. 076
  123.        }
  124. 077

  125. 078
  126.         
  127. 079

  128. 080
  129.        //读取Cookie,自动完成登陆操作----------------------------------------------------------------
  130. 081

  131. 082
  132.        //在Filter程序中调用该方法,见AutoLogonFilter.java
  133. 083

  134. 084
  135.        public static void readCookieAndLogon(HttpServletRequest request, HttpServletResponse response,
  136. 085

  137. 086
  138. FilterChain chain) throws IOException, ServletException,UnsupportedEncodingException{
  139. 087
  140.        //根据cookieName取cookieValue
  141. 088
  142.        Cookie cookies[] = request.getCookies();
  143. 089
  144.                      String cookieValue = null;
  145. 090
  146.                      if(cookies!=null){
  147. 091
  148.                             for(int i=0;i
  149. 092
  150.                                    if (cookieDomainName.equals(cookies[i].getName())) {
  151. 093
  152.                                           cookieValue = cookies[i].getValue();
  153. 094
  154.                                           break;
  155. 095
  156.                                    }
  157. 096

  158. 097
  159.                             }
  160. 098

  161. 099
  162.                      }
  163. 100
  164.                      //如果cookieValue为空,返回,
  165. 101
  166.                      if(cookieValue==null){
  167. 102
  168.                             return;
  169. 103
  170.                      }
  171. 104
  172.               //如果cookieValue不为空,才执行下面的代码
  173. 105
  174.               //先得到的CookieValue进行Base64解码
  175. 106
  176.               String cookieValueAfterDecode = new String (Base64.decode(cookieValue),"utf-8");
  177. 107
  178.               //对解码后的值进行分拆,得到一个数组,如果数组长度不为3,就是非法登陆
  179. 108
  180.               String cookieValues[] = cookieValueAfterDecode.split(":");
  181. 109
  182.               if(cookieValues.length!=3){
  183. 110
  184.                      response.setContentType("text/html;charset=utf-8");
  185. 111
  186.                      PrintWriter out = response.getWriter();
  187. 112
  188.                      out.println("你正在用非正常方式进入本站...");
  189. 113
  190.                      out.close();
  191. 114
  192.                      return;
  193. 115
  194.               }
  195. 116
  196.               //判断是否在有效期内,过期就删除Cookie
  197. 117
  198.               long validTimeInCookie = new Long(cookieValues[1]);
  199. 118
  200.               if(validTimeInCookie < System.currentTimeMillis()){
  201. 119
  202.                      //删除Cookie
  203. 120
  204.                      clearCookie(response);
  205. 121
  206.                      response.setContentType("text/html;charset=utf-8");
  207. 122
  208.                      PrintWriter out = response.getWriter();
  209. 123
  210.                      out.println("");你的Cookie已经失效,请重新登陆
  211. 124
  212.                      out.close();
  213. 125
  214.                      return;
  215. 126
  216.               }
  217. 127
  218.               //取出cookie中的用户名,并到数据库中检查这个用户名,
  219. 128
  220.               String username = cookieValues[0];
  221. 129
  222.                
  223. 130
  224.               //根据用户名到数据库中检查用户是否存在
  225. 131
  226.               UserDAO ud = DaoImplFactory.getInstance();
  227. 132
  228.               User user = ud.selectUserByUsername(username);
  229. 133

  230. 134
  231.               //如果user返回不为空,就取出密码,使用用户名+密码+有效时间+ webSiteKey进行MD5加密
  232. 135
  233.               if(user!=null){
  234. 136
  235.                      String md5ValueInCookie = cookieValues[2];
  236. 137
  237.                      String md5ValueFromUser =getMD5(user.getUserName() + ":" + user.getPassword()
  238. 138
  239.                                    + ":" + validTimeInCookie + ":" + webKey);
  240. 139
  241.                      //将结果与Cookie中的MD5码相比较,如果相同,写入Session,自动登陆成功,并继续用户请求
  242. 140
  243.                      if(md5ValueFromUser.equals(md5ValueInCookie)){
  244. 141
  245.                             HttpSession session = request.getSession(true);
  246. 142
  247.                             session.setAttribute("user", user);
  248. 143
  249.                             chain.doFilter(request, response);
  250. 144
  251.                      }
  252. 145

  253. 146
  254.               }else{
  255. 147

  256. 148
  257.               //返回为空执行
  258. 149
  259.                      response.setContentType("text/html;charset=utf-8");
  260. 150
  261.                      PrintWriter out = response.getWriter();
  262. 151
  263.                      out.println("cookie验证错误!");
  264. 152
  265.                      out.close();
  266. 153
  267.                return;
  268. 154

  269. 155
  270.              }
  271. 156

  272. 157
  273.        }
  274. 158

  275. 159
  276.         
  277. 160

  278. 161
  279.        //用户注销时,清除Cookie,在需要时可随时调用-----------------------------------------------------
  280. 162
  281.        public static void clearCookie( HttpServletResponse response){
  282. 163
  283.               Cookie cookie = new Cookie(cookieDomainName, null);
  284. 164
  285.               cookie.setMaxAge(0);
  286. 165
  287.               cookie.setPath("/");
  288. 166
  289.               response.addCookie(cookie);
  290. 167
  291.        }
  292. 168

  293. 169
  294. //获取Cookie组合字符串的MD5码的字符串----------------------------------------------------------------
  295. 170
  296.               public static String getMD5(String value) {
  297. 171
  298.                      String result = null;
  299. 172
  300.                      try{
  301. 173
  302.                             byte[] valueByte = value.getBytes();
  303. 174
  304.                             MessageDigest md = MessageDigest.getInstance("MD5");
  305. 175
  306.                             md.update(valueByte);
  307. 176
  308.                             result = toHex(md.digest());
  309. 177
  310.                      } catch (NoSuchAlgorithmException e2){
  311. 178
  312.                             e1.printStackTrace();
  313. 179
  314.                      }
  315. 180
  316.                      return result;
  317. 181
  318.               }
  319. 182
  320.       //将传递进来的字节数组转换成十六进制的字符串形式并返回
  321. 183
  322.               private static String toHex(byte[] buffer){
  323. 184
  324.                      StringBuffer sb = new StringBuffer(buffer.length * 2);
  325. 185
  326.                      for (int i = 0; i < buffer.length; i++){
  327. 186
  328.                             sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
  329. 187
  330.                             sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
  331. 188
  332.                      }
  333. 189
  334.                      return sb.toString();
  335. 190
  336.               }
  337. 191
  338. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP