쿠키를 읽으려면 javax.servlet.http.Cookie 배열을 생성해야 합니다. getCookies( )를 호출하여 객체 HttpServletRequest 메소드 . 그런 다음 배열을 순환하고 getName()을 사용합니다. 및 getValue() 각 쿠키 및 관련 값에 액세스하는 방법.
이제 이전 예에서 설정한 쿠키를 읽어보겠습니다. −
예시
<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];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html> 이제 위의 코드를 main.jsp에 넣습니다. 파일에 액세스를 시도합니다. 이름 쿠키를 설정한 경우 "John" 및 last_name 쿠키로 "Player"로 입력한 다음 https://localhost:8080/main.jsp 실행 다음 결과를 표시합니다 -
출력
Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player