쿠키를 삭제하는 방법은 매우 간단합니다. 쿠키를 삭제하려면 다음 세 단계를 따르기만 하면 됩니다. -
-
이미 존재하는 쿠키를 읽어 쿠키 객체에 저장합니다.
-
setMaxAge()를 사용하여 쿠키 사용 기간을 0으로 설정 기존 쿠키를 삭제하는 방법입니다.
-
이 쿠키를 응답 헤더에 다시 추가하십시오.
다음 예에서는 "first_name"이라는 기존 쿠키를 삭제하는 방법을 보여줍니다. 다음에 main.jsp JSP를 실행하면 first_name에 대해 null 값이 반환됩니다.
예시
<html>
<head>
<title>Reading Cookies</title>
</head>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;
// Get an array of Cookies associated with the this domain
cookies = request.getCookies();
if( cookies != null ) {
out.println("<h2> Found Cookies Name and Value</h2>");
for (int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html> 이제 위의 코드를 main.jsp에 넣습니다. 파일에 액세스를 시도합니다. 다음 결과가 표시됩니다 -
출력
Cookies Name and Value Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player
이제 https://localhost:8080/main.jsp를 실행합니다. 다시 한 번 다음과 같이 하나의 쿠키만 표시해야 합니다. -
Found Cookies Name and Value Name : last_name, Value: Player
Internet Explorer에서 쿠키를 수동으로 삭제할 수 있습니다. 도구 메뉴에서 시작하고 인터넷 옵션을 선택합니다. 모든 쿠키를 삭제하려면 쿠키 삭제 버튼을 클릭하십시오.