자바 쿠키 는 사용자 계 정 정보 로 컬 저장 을 실현 합 니 다.

11176 단어
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();          
 }

좋은 웹페이지 즐겨찾기