Cookie

Cookie

  • http프로토콜은 웹브라우저에게 응답 후 연결을 끊음
  • cookie연결이 끊겼을 때 어떤 정보를 지속적으로 유지하기 위한 수단
  • 서버에 생성하여 서버가 아닌 클라이언트측에 특정 정보를 저장함
  • 서버에 요청할 때 마다 쿠키의 속성값을 참조, 변경 할 수 있음
  • 4kb로 용량이 제한적이며, 300개까지 데이터 정보를 가질 수 있음

Grammar

  1. 쿠키 생성 - 쿠키 클래스 이용
  2. 속성 설정 - setter이용
  3. response객체에 쿠키 탑재 - response.addCookie() 이용

Method

1
2
3
4
5
6
7
8
9
10
setMaxAge() - 쿠키 유효시간 설정
setPath() - 쿠키사용의 유효 디렉토리 설정
setValue() - 쿠키의 값을 설정
setVersion() - 쿠키 버전 설정

getMaxAge() - 쿠키 유효기간 정보 획득
getName() - 쿠키 이름 획득
getPath() - 쿠키사용의 유효 디렉토리 정보 획득
getValue() - 쿠키의 값 획득
getVersion() - 쿠키 버전 정보 획득

Example

  • cookieSet.jsp

    1
    2
    3
    4
    5
    6
    7
    8

    <%
    Cookie cookie = new Cookie("cookieName","cookieValue");
    cookie.setMaxAge(60*60); //1시간
    response.addCookie(cookie);
    %>

    <a href = "cookieGet.jsp">cookie get</a>
  • cookieGet.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <%
    Cookie[] cookies = request.getCookies(); //쿠키 전부 배열로 가져옴

    for(int i=0; i<cookies.length;i++){
    // 각 쿠키를 돌면서 정보 확인
    String str = cookies[i].getName();
    if(str.equals("cookieName")){
    out.println("cookies["+i+"] name: " + cookies[i].getName() + "<br/>");
    out.println("cookies["+i+"] value: " + cookies[i].getValue() + "<br/>");
    out.println("===================<br/>")
    }
    }
    %>

    <a href="cookieDel.jsp">cookie delete</a>
  • cookieDel.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    <%
    Cookie[] cookies = request.getCookies();

    for(int i=0; i<cookies.length;i++){
    String str = cookies[i].getName();
    if(str.equals("cookieName")){
    out.println("cookies["+i+"] name: " + cookies[i].getName() + "<br/>");
    out.println("cookies["+i+"] value: " + cookies[i].getValue() + "<br/>");

    cookies[i].setMaxAge(0); // 유효시간 0초로 해서 삭제
    response.addCookie(cookies[i]); // 속성 변경 후 다시 탑재해서 이어나감
    }
    }
    %>

    <a href="cookieTest.jsp">cookie Test</a>
  • cookieTest.jsp

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <%
    Cookie[] cookies = request.getCookies();

    if(cookies != null){
    for(int i=0; i<cookies.length;i++){
    out.println("cookies["+i+"] name: " + cookies[i].getName() + "<br/>");
    out.println("cookies["+i+"] value: " + cookies[i].getValue() + "<br/>");
    }
    }
    %>

속성 변경시 response객체에 꼭 다시 넣어줘야함

Comments