자바 쿠키 는 사용자 계 정 정보 로 컬 저장 을 실현 합 니 다.
package cn.itcast.util;  import java.io.IOException;  import java.io.PrintWriter;  import java.io.UnsupportedEncodingException;  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 java.security.MessageDigest;  import java.security.NoSuchAlgorithmException;  import cn.itcast.bean.User;  import cn.itcast.dao.UserDAO;  import cn.itcast.factory.DaoImplFactory;  import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;  /*  * 2007.09.21 by lyhapple  * */  public class CookieUtil {         //  cookie  cookieName         private final static String cookieDomainName = “cn.itcast”;                  //  cookie                private final static String webKey = “itcast”;           //  cookie        ,                private final static long cookieMaxAge = 60 * 60 * 24 * 7 * 2;                  //  Cookie    --------------------------------------------------------------------------------------------------------         // CheckLogonServlet.java             //     user                            public static void saveCookie(User user, HttpServletResponse response) {                                //cookie                    long validTime = System.currentTimeMillis() + (cookieMaxAge * 1000);                                //MD5                        String cookieValueWithMd5 =getMD5(user.getUserName() + ":" + user.getPassword()                              + ":" + validTime + ":" + webKey);                                //         Cookie                 String cookieValue = user.getUserName() + ":" + validTime + ":" + cookieValueWithMd5;                                //    Cookie    BASE64                  String cookieValueBase64 = new String(Base64.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                                     if (cookieDomainName.equals(cookies[i].getName())) {                                            cookieValue = cookies[i].getValue();                                            break;                                     }                              }                       }                       //  cookieValue  ,  ,                       if(cookieValue==null){                              return;                       }                                //  cookieValue   ,                        //    CookieValue  Base64                  String cookieValueAfterDecode = new String (Base64.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 e2){                              e1.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();                }  }이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.