- 論壇徽章:
- 0
|
今天做一個(gè)項(xiàng)目就是有一個(gè)記住用戶名的,選中復(fù)選框則記住用戶名和密碼,下次登錄的時(shí)候就方便用戶名的登陸:- package com.laizhi.util;
- 002
-
- 003
- import java.io.IOException;
- 004
-
- 005
- import java.io.PrintWriter;
- 006
-
- 007
- import java.io.UnsupportedEncodingException;
- 008
-
- 009
- import javax.servlet.FilterChain;
- 010
-
- 011
- import javax.servlet.ServletException;
- 012
-
- 013
- import javax.servlet.http.Cookie;
- 014
-
- 015
- import javax.servlet.http.HttpServletRequest;
- 016
-
- 017
- import javax.servlet.http.HttpServletResponse;
- 018
-
- 019
- import javax.servlet.http.HttpSession;
- 020
-
- 021
- import java.security.MessageDigest;
- 022
-
- 023
- import java.security.NoSuchAlgorithmException;
- 024
-
- 025
- import com.laizhi.bean.User;
- 026
-
- 027
- import com.laizhi.dao.UserDAO;
- 028
-
- 029
- import com.laizhi.factory.DaoImplFactory;
- 030
-
- 031
- import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
- 032
-
- 033
- /*
- 034
-
- 035
- * 2014.07.01
- 036
-
- 037
- * */
- 038
-
- 039
- public class CookieUtil {
- 040
- //保存cookie時(shí)的cookieName
- 041
- private final static String cookieDomainName = “l(fā)aizhi”;
- 042
- //加密cookie時(shí)的網(wǎng)站自定碼
- 043
-
- 044
- private final static String webKey = “123456”;
- 045
- //設(shè)置cookie有效期是兩個(gè)星期,根據(jù)需要自定義
- 046
- private final static long cookieMaxAge = 60 * 60 * 24 * 7 * 2;
- 047
- //保存Cookie到客戶端-------------------------------------------------------------------------
- 048
- //在CheckLogonServlet.java中被調(diào)用
- 049
- //傳遞進(jìn)來的user對象中封裝了在登陸時(shí)填寫的用戶名與密碼
- 050
-
- 051
- public static void saveCookie(User user, HttpServletResponse response) {
- 052
- //cookie的有效期
- 053
- long validTime = System.currentTimeMillis() + (cookieMaxAge * 5000);
- 054
- //MD5加密用戶詳細(xì)信息
- 055
- String cookieValueWithMd5 =getMD5(user.getUserName() + ":" + user.getPassword()
- 056
-
- 057
- + ":" + validTime + ":" + webKey);
- 058
- //將要被保存的完整的Cookie值
- 059
- String cookieValue = user.getUserName() + ":" + validTime + ":" + cookieValueWithMd5;
- 060
- //再一次對Cookie的值進(jìn)行BASE64編碼
- 061
-
- 062
- String cookieValueBase64 = new String(Base64.encode(cookieValue.getBytes()));
- 063
- //開始保存Cookie
- 064
- Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
- 065
- //存兩年(這個(gè)值應(yīng)該大于或等于validTime)
- 066
- cookie.setMaxAge(60 * 60 * 24 * 365 * 2);
- 067
-
- 068
- //cookie有效路徑是網(wǎng)站根目錄
- 069
-
- 070
- cookie.setPath("/");
- 071
-
- 072
- //向客戶端寫入
- 073
-
- 074
- response.addCookie(cookie);
- 075
-
- 076
- }
- 077
-
- 078
-
- 079
-
- 080
- //讀取Cookie,自動完成登陸操作----------------------------------------------------------------
- 081
-
- 082
- //在Filter程序中調(diào)用該方法,見AutoLogonFilter.java
- 083
-
- 084
- public static void readCookieAndLogon(HttpServletRequest request, HttpServletResponse response,
- 085
-
- 086
- FilterChain chain) throws IOException, ServletException,UnsupportedEncodingException{
- 087
- //根據(jù)cookieName取cookieValue
- 088
- Cookie cookies[] = request.getCookies();
- 089
- String cookieValue = null;
- 090
- if(cookies!=null){
- 091
- for(int i=0;i
- 092
- if (cookieDomainName.equals(cookies[i].getName())) {
- 093
- cookieValue = cookies[i].getValue();
- 094
- break;
- 095
- }
- 096
-
- 097
- }
- 098
-
- 099
- }
- 100
- //如果cookieValue為空,返回,
- 101
- if(cookieValue==null){
- 102
- return;
- 103
- }
- 104
- //如果cookieValue不為空,才執(zhí)行下面的代碼
- 105
- //先得到的CookieValue進(jìn)行Base64解碼
- 106
- String cookieValueAfterDecode = new String (Base64.decode(cookieValue),"utf-8");
- 107
- //對解碼后的值進(jìn)行分拆,得到一個(gè)數(shù)組,如果數(shù)組長度不為3,就是非法登陸
- 108
- String cookieValues[] = cookieValueAfterDecode.split(":");
- 109
- if(cookieValues.length!=3){
- 110
- response.setContentType("text/html;charset=utf-8");
- 111
- PrintWriter out = response.getWriter();
- 112
- out.println("你正在用非正常方式進(jìn)入本站...");
- 113
- out.close();
- 114
- return;
- 115
- }
- 116
- //判斷是否在有效期內(nèi),過期就刪除Cookie
- 117
- long validTimeInCookie = new Long(cookieValues[1]);
- 118
- if(validTimeInCookie < System.currentTimeMillis()){
- 119
- //刪除Cookie
- 120
- clearCookie(response);
- 121
- response.setContentType("text/html;charset=utf-8");
- 122
- PrintWriter out = response.getWriter();
- 123
- out.println("");你的Cookie已經(jīng)失效,請重新登陸
- 124
- out.close();
- 125
- return;
- 126
- }
- 127
- //取出cookie中的用戶名,并到數(shù)據(jù)庫中檢查這個(gè)用戶名,
- 128
- String username = cookieValues[0];
- 129
-
- 130
- //根據(jù)用戶名到數(shù)據(jù)庫中檢查用戶是否存在
- 131
- UserDAO ud = DaoImplFactory.getInstance();
- 132
- User user = ud.selectUserByUsername(username);
- 133
-
- 134
- //如果user返回不為空,就取出密碼,使用用戶名+密碼+有效時(shí)間+ webSiteKey進(jìn)行MD5加密
- 135
- if(user!=null){
- 136
- String md5ValueInCookie = cookieValues[2];
- 137
- String md5ValueFromUser =getMD5(user.getUserName() + ":" + user.getPassword()
- 138
- + ":" + validTimeInCookie + ":" + webKey);
- 139
- //將結(jié)果與Cookie中的MD5碼相比較,如果相同,寫入Session,自動登陸成功,并繼續(xù)用戶請求
- 140
- if(md5ValueFromUser.equals(md5ValueInCookie)){
- 141
- HttpSession session = request.getSession(true);
- 142
- session.setAttribute("user", user);
- 143
- chain.doFilter(request, response);
- 144
- }
- 145
-
- 146
- }else{
- 147
-
- 148
- //返回為空執(zhí)行
- 149
- response.setContentType("text/html;charset=utf-8");
- 150
- PrintWriter out = response.getWriter();
- 151
- out.println("cookie驗(yàn)證錯誤!");
- 152
- out.close();
- 153
- return;
- 154
-
- 155
- }
- 156
-
- 157
- }
- 158
-
- 159
-
- 160
-
- 161
- //用戶注銷時(shí),清除Cookie,在需要時(shí)可隨時(shí)調(diào)用-----------------------------------------------------
- 162
- public static void clearCookie( HttpServletResponse response){
- 163
- Cookie cookie = new Cookie(cookieDomainName, null);
- 164
- cookie.setMaxAge(0);
- 165
- cookie.setPath("/");
- 166
- response.addCookie(cookie);
- 167
- }
- 168
-
- 169
- //獲取Cookie組合字符串的MD5碼的字符串----------------------------------------------------------------
- 170
- public static String getMD5(String value) {
- 171
- String result = null;
- 172
- try{
- 173
- byte[] valueByte = value.getBytes();
- 174
- MessageDigest md = MessageDigest.getInstance("MD5");
- 175
- md.update(valueByte);
- 176
- result = toHex(md.digest());
- 177
- } catch (NoSuchAlgorithmException e2){
- 178
- e1.printStackTrace();
- 179
- }
- 180
- return result;
- 181
- }
- 182
- //將傳遞進(jìn)來的字節(jié)數(shù)組轉(zhuǎn)換成十六進(jìn)制的字符串形式并返回
- 183
- private static String toHex(byte[] buffer){
- 184
- StringBuffer sb = new StringBuffer(buffer.length * 2);
- 185
- for (int i = 0; i < buffer.length; i++){
- 186
- sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
- 187
- sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
- 188
- }
- 189
- return sb.toString();
- 190
- }
- 191
- }
復(fù)制代碼 |
|