쿠키 저장 및 조회 from JAVA (자바)

 

 

 

 

 

 

 

 

 

 

사용예)

@Override
public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
            
    Cookie[] cookies = request.getCookies();
    String cUID = null;
    if(cookies!= null && cookies.length > 0){
        cUID = CookieUtil.getCookie(request, "MYUID");//쿠키에 저장된 UID 가져오기
    }
    if(cUID == null || "".equals(cUID)){
        //**************************쿠키설정 시작**************************//
        Cookie uidCookie = new Cookie("MYUID", sUID);
        uidCookie.setMaxAge(86400);
        response.addCookie(uidCookie);
        //**************************쿠키설정 끝****************************//
    }else{

    }
	return true;
}

private boolean checkSession(HttpServletRequest request, HttpServletResponse response) throws Exception {
    boolean returnValue = false;
    String member_id = "";

    if(returnValue){
    return returnValue;
    }

    // 1. getHttpSession
    HttpSession session = request.getSession(true);

    // 1-1. 사용자가 자동로그인(로그인유지설정) 설정했을 경우 자동로그인 된다.
    String myLoginCookie = CookieUtil.getCookie(request, "myLoginCookie");
    String pwlookLoginCookie = CookieUtil.getCookie(request, "pwlookLoginCookie");
    logger.debug("===================== 쿠키 정보 확인 Start =====================");
    logger.debug("myLoginCookie {}.", myLoginCookie);
    logger.debug("pwlookLoginCookie {}.", pwlookLoginCookie);
    logger.debug("===================== 쿠키 정보 확인 End =====================");

    if(!"".equals(myLoginCookie) && !"".equals(pwlookLoginCookie)){
    //로그인쿠키 정보 있을경우 해당 id 조회후 세션 재생성
    HashMap<String, String> mp = new HashMap<String, String>();
    mp.put("MEMBER_ID", myLoginCookie);
    mp.put("PWD", pwlookLoginCookie);

    QueryEntry entry = queryService.querySelectOne("mallUserSelect.Q002", mp);
    if(entry.getQueryCode() == MallMessage.QS000){
    session.setAttribute("member_id", entry.getFetchResultSet().get("MEMBER_ID"));
    session.setAttribute("member_nm", entry.getFetchResultSet().get("MEMBER_NM"));
    }

    logger.debug("===================== 쿠키 정보 확인 후 세션 재생성 Start =====================");
    logger.debug("member_id {}.", session.getAttribute("member_id"));
    logger.debug("member_nm {}.", session.getAttribute("member_nm"));
    logger.debug("===================== 쿠키 정보 확인 후 세션 재생성 End =====================");

    }

    // 2. check session
    if (session != null) {
    member_id = (String) session.getAttribute("member_id");

    if (member_id != null && !"".equals(member_id)) {
    returnValue = true;
    }
    }// end of if
    return returnValue;
} 

 

 

CookieUtil.java 파일 

 

package com.mysite.mobile.common.util;

import java.io.UnsupportedEncodingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil 
{
	/**
	 * setCookie
	 * 
	 * @return 
	 * @throws Exception
	 */
	public static void setCookie(HttpServletResponse response, int key, String value) throws Exception {
//		System.out.println("VALUE >>>>>>>> " + value);
//		System.out.println("key >>>>>>>> " + key);
		value = java.net.URLEncoder.encode(value.toString(), "UTF-8");
		Cookie cookie = new Cookie("cookie"+key, value);
	System.out.println("cookie name >>>>>>>> " + cookie.getName());
	System.out.println("cookie value >>>>>>>> " + cookie.getValue());
		cookie.setDomain("futurebook.com");
		cookie.setMaxAge(60*60);
		//cookie.setPath("/");
    	response.addCookie(cookie);
	}
	
	/**
	 * setCookie
	 * 
	 * @return 
	 * @throws Exception
	 */
	public static void setCookie(HttpServletRequest request, HttpServletResponse response, String key, String value, int day) throws Exception {
//		System.out.println("VALUE >>>>>>>> " + value);
//		System.out.println("key >>>>>>>> " + key);
		value = java.net.URLEncoder.encode(value.toString(), "UTF-8");
		Cookie cookie = new Cookie(key, value);
		System.out.println("cookie name >>>>>>>> " + cookie.getName());
		System.out.println("cookie value >>>>>>>> " + cookie.getValue());
		System.out.println("cookie getServerName >>>>>>>> " +request.getServerName());
		cookie.setDomain(request.getServerName());
		cookie.setMaxAge(day * 24 * 60 * 60);//30일
		//cookie.setPath("/");
    	response.addCookie(cookie);
	}	
	/**
	 * 쿠키 삭제
	 * 
	 * @return 
	 * @throws Exception
	 */
	
	public static void delCookie(HttpServletResponse response, String key, String domain) throws Exception {
//		Cookie cookie = new Cookie("cookie"+key, java.net.URLEncoder.encode(value.toString(), "UTF-8"));
		
		Cookie cookie = new Cookie(key, "0");
		cookie.setMaxAge(0);
		cookie.setDomain(domain);
//		cookie.setPath("/");
    	response.addCookie(cookie);


		System.out.println("cookie del name >>>>>>>> " + cookie.getName());
		System.out.println("cookie del value >>>>>>>> " + cookie.getValue());
		System.out.println("cookie del domain >>>>>>>> " + domain);
	}
	
	
	public static void setCookie2(HttpServletResponse response, int key, String value) throws Exception {
//		Cookie cookie = new Cookie("cookie"+key, java.net.URLEncoder.encode(value.toString(), "UTF-8"));
		Cookie cookie = new Cookie("cookie"+key, "0");
		cookie.setMaxAge(0);
		cookie.setDomain("futurebook.com");
		//cookie.setPath("/");
    	response.addCookie(cookie);


		System.out.println("cookie del name >>>>>>>> " + cookie.getName());
		System.out.println("cookie del value >>>>>>>> " + cookie.getValue());
	}
	
	
	/**
	 * utf-8로 변환하지 않고 저장
	 * 
	 * @return 
	 * @throws Exception
	 */
	public static void setCookie3(HttpServletResponse response, int key, String value) throws Exception {
		Cookie cookie = new Cookie("cookie"+key, value);
		cookie.setDomain("futurebook.com");
//		System.out.println("cookie add key >>>>>>>> " + key);
//		System.out.println("cookie add value >>>>>>>> " + value);
		cookie.setMaxAge(60*60);
		//cookie.setPath("/");
    	response.addCookie(cookie);
	}
	

	/**
	 * getCookie
	 * 
	 * @return cookie
	 * @throws Exception
	 */
    public static String getCookie(HttpServletRequest request, String key) throws Exception {
    	Cookie[] cookies = request.getCookies();
    	if(key == null) return null;
    	String value = "";
    	if(cookies != null){
        	for(int i=0;i<cookies.length;i++){
        		if(key.equals(cookies[i].getName())){
        			value = java.net.URLDecoder.decode(cookies[i].getValue(), "UTF-8");
        			break;
        		}
        	}    		
    	}

		return value;
	}
    
    /**
	 * getProdCookie
	 * 쿠키안에 상품코드|상품명|가격|이미지경로 정보형식으로 최근본상품 정보가 담겨있음.
	 * @return cookie value - 상품코드|상품명|가격|이미지경로^상품코드|상품명|가격|이미지경로^상품코드|상품명|가격|이미지경로 ... ^구분자로 정보를 구분함. 
	 * @throws Exception
	 */
    public static String getProdCookie(HttpServletRequest request, String prodCookieName) throws Exception {
    	
    	Cookie[] cookies = request.getCookies();
    	
    	String list = "";

    	for(int i=0; i < cookies.length; i++){
    		Cookie ca = cookies[i];
    		String value = ca.getValue();
//    		String tmp = ca.getValue().replaceAll("%", "%25");
//    		String value = new String(URLDecoder.decode(tmp,"utf-8"));
//    		value.replace("%25", "%");
    		
    		if(ca.getName().contains(prodCookieName)){
    			if(list == ""){
            		list = value;	
            	}else{
            		list = list + "^" + value;
            	}
    		}
    		
    		System.out.println("list = "+list);
    	}
    	
		return list;
	}
    
    // 쿠키에 저장된 데이터 인지 확인
    public static boolean getCookieDupCheck(HttpServletRequest request, String value) throws UnsupportedEncodingException{
    	Cookie[] cookies = request.getCookies();
    	
    	for(int i=0;i<cookies.length;i++){
    		if(java.net.URLEncoder.encode(value.toString(), "UTF-8").equals(cookies[i].getValue())){
    			return true;
    		}
    	}
    	
    	return false;
    }
    
    // 5번째에 새로운 쿠키 추가 (가장 먼저 등록된 쿠키는 삭제)
    public static void setCookieAdd(HttpServletRequest request, HttpServletResponse response, String value) throws Exception {
    	Cookie[] cookies = request.getCookies();
    	int idx = 1;
    	for(int i=0;i<cookies.length;i++){
    		if(cookies[i].getName().length() > 6){
    			if(idx == 5){
    				break;
    			}    			
    			if(!"cookie1".equals(cookies[i].getName().trim())){
		    		if("cookie".equals(cookies[i].getName().subSequence(0, 6))){
		       			setCookie3(response, idx, cookies[i].getValue());
		       			idx = idx +1;
					}
    			}
    		}
    	}
    	setCookie(response, 5, value);
    }

    // 해당 쿠키를 삭제
    public static void setCookieRemove(HttpServletRequest request, HttpServletResponse response, String value) throws Exception {
    	Cookie[] cookies = request.getCookies();
    	int cnt = 1;
    	
    	for(int i=1;i<cookies.length;i++){
    		if(!cookies[i-1].getValue().equals(java.net.URLEncoder.encode(value.toString(), "UTF-8"))){
    			setCookie3(response, cnt, cookies[i-1].getValue());
    			System.out.println(cnt + ", "+ java.net.URLDecoder.decode(cookies[i-1].getValue(), "utf-8"));
    			cnt++;
    		}
    	}
    	setCookie2(response, cookies.length - 1, value);
    }
    // 해당 쿠키를 삭제
    public static void setCookieRemove(HttpServletRequest request, HttpServletResponse response, int key , String value) throws Exception {

    	setCookie2(response, key, "");
    	
    	Cookie[] cookies = request.getCookies();
    	int idx = 1;
    	for(int i=cookies.length; i==0; i--){
    		if(cookies[i].getName().length() > 6){
    			//System.out.println(i + ", "+ java.net.URLDecoder.decode(cookies[i].getValue(), "utf-8"));
//    			if("cookie".equals(cookies[i].getName().subSequence(0, 6))){
//	       			setCookie3(response, idx, cookies[i].getValue());
//	       			idx = idx +1;
//				}
    		}
    	}
    }
}

 

 

+ Recent posts