프로그래밍/JSP Servlet

JSP/Servlet - 쿠키(Cookie) 사용 방법

가카리 2015. 12. 27. 21:04
반응형

1. 새로운 쿠키 데이터를 저장하는 방법 - 입력

 

1) Cookie 클래스의 객체를 만든다. (javax.servlet.http 패키지)

2) addCookie 메소드를 호출한다.

 

예제 StoreCookies.jsp 파일

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    //쿠키 저장시 보통 html보다 앞에 와야한다.

    response.addCookie(new Cookie("NAME", "John"));

    response.addCookie(new Cookie("GENDER", "Male"));

    response.addCookie(new Cookie("AGE", "15"));

%>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    쿠키 저장 완료<br>

    

</body>

</html>

 

출력화면

 

 

2. 쿠키 데이터 읽는 방법 - 조회

 

1) request 내장 변수로 getCookie 메소드를 호출한다.

2)Cookie 객체에 대해 getName메소드와 getValue메소드를 이용해서 쿠키 데이터를 가져온다.

    

예제 ReadCookies.jsp 파일

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<% Cookie[] cookies = request.getCookies(); %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    이름 : <%= getCookieValue(cookies, "NAME") %> <BR>

    성별 : <%= getCookieValue(cookies, "GENDER") %> <BR>

    나이 : <%= getCookieValue(cookies, "AGE") %>

</body>

</html>

<%!

    private String getCookieValue(Cookie[] cookies, String name){

        if(cookies == null)

            return null;

        

        //cookie cookies 배열의 객체를 한개씩 넣어서 cookies 배열 길이만큼 돌리라는 의미

        for(Cookie cookie : cookies){

            if(cookie.getName().equals(name))

                return cookie.getValue();

        }

        return null;

}

%>

 

출력화면

 

3. 쿠키 데이터를 수정 - 수정 기능

 

1) 쿠키를 저장할 때와 마찬가지로 Cookie 객체를 만들어서 addCookie 메소드에 넘겨주면 됩니다.

 

예제 ModifyCookies.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    response.addCookie(new Cookie("AGE", "16"));

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    수정 완료

</body>

</html>

 

 

실행 화면

 

 

다시 ReadCookies.jsp를 실행해보면 나이가 16으로 바뀐 것을 확인할 수 있다.

 

 

 

4. 쿠키 데이터를 삭제 - 삭제 기능

 

쿠키에 수명을 지정해 놓으면 웹브라우저를 시작하고 끝내난 동작과 상관없이 그 쿠키가 일정 기간동안 보존됩니다.

 

쿠키의 수명을 지정하기 위해서는 addCookie메소드를 호출하기 전에 Cookie 객체에 대해 setMaxAge라는 메소드를 호출하면 됩니다.

 

파라미터로 0을 넘겨주면 쿠키를 바로 삭제할 수 있습니다.

 

파라미터로 -1을 넘겨주면 웹브라우저가 끝날 때 쿠키가 삭제되도록 합니다.

 

예제 DeleteCookies.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    Cookie cookie = new Cookie("GENDER", "");//삭제할 쿠키이므로 아무값이나 넘겨주면됩니다.

    cookie.setMaxAge(0);

    response.addCookie(cookie);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    쿠키 삭제 완료<BR>

</body>

</html>

 

실행 화면

 

 

그 다음 ReadCookies.jsp 을 실행해보면 성별이 null값으로 변했음을 알 수 있다.

 

 

5. 쿠키가 특정 경로명을 갖는 URL로만 전송되도록 만드는 방법

 

전송범위를 특정경로로 좁혀야 할 경우 addCookie 메소드를 호출하기 전에 Cookie 객체에 대해 setPath메소드를 호출하면 됩니다.

 

cookie.setPath("/ch4_jsp/");

 

이번에는 다음과 같이 예제를 구성합니다.

 

 

예제 StoreJobCookie.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    Cookie cookie = new Cookie("JOB", "programmer");

    cookie.setPath("/ch4_jsp/sub1");//여기만 보내게 저장함.

    response.addCookie(cookie);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    쿠키 저장 완료.

</body>

</html>

 

실행 화면

 

/sub1/ReadCookie.jsp와 /sub2/ReadCookie.jsp는 다음과 같이 동일입니다.

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    Cookie[] cookies = request.getCookies();

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    job : <%= getCookieValue(cookies, "JOB") %> <BR>

</body>

</html>

<%!

    private String getCookieValue(Cookie[] cookies, String name){

        String value = null;

        if(cookies == null)

            return null;

        for(Cookie cookie : cookies){

            if(cookie.getName().equals(name))

                return cookie.getValue();

        }

        return null;

}

 

%>    

 

 

실행 화면

/sub1/ReadCookie.jsp 실행 시

 

/sub2/ReadCookie.jsp 실행 시

 

6. 쿠키가 여러 웹 서버로 전송되도록 만드는 방법

 

여러 웹서버로 전송하기 위해서는 setDomain이라는 메소드를 호출하면 됩니다.

 

도메인을 지정할 때 ".naver.com "처럼 대표적인 도메인 이름을 지정해야 합니다.

 

이렇게 지정한 쿠키를 웹브라우저로 보내면 도메인 이름을 쿠키데이터와 함께 저장할 것입니다.

 

예제 StoreIDCookie.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    Cookie cookie = new Cookie("LOGIN_ID", "abc123");

    cookie.setDomain(".naver.com");

    response.addCookie(cookie);

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    저장 완료

</body>

</html>

 

 

쿠키 데이터 읽기 예제 ReadIDCookie.jsp

 

<%@ page language="java" contentType="text/html; charset=EUC-KR"

pageEncoding="EUC-KR"%>

<%

    Cookie[] cookies = request.getCookies();

%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">

<title>Insert title here</title>

</head>

<body>

    LOGIN_ID: <%= getCookieValue(cookies, "LOGIN_ID") %>

</body>

</html>

<%!

    private String getCookieValue(Cookie[] cookies, String name){

        String value = null;

        if(cookies == null)

            return null;

        for(Cookie cookie : cookies){

            if(cookie.getName().equals(name))

                return cookie.getValue();

        }

        return null;

}

%>

 

실행은 웹서버가 여러 대 필요해서 해보지 못했습니다.

반응형