쿠키를 이용한 카운터
pageEncoding=”EUC-KR”%>
<!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>
<%
Cookie [] cookieArray = request.getCookies(); // 브라우저에서 전달된 모든 쿠키 저장
Cookie cookie = null;
int countNum = 0;
String countStr = “”;
if(cookieArray != null) { // 브라우저에서 전달된 쿠키정보가 있다면
for(int i = 0; i < cookieArray.length; i++) { // 전달된 모든 쿠키를 검사하며,
if(cookieArray[i].getName().equals(“counter”)) { // “counter”란 이름의 쿠키정보를 찾아
cookie = cookieArray[i]; // 저장하고
break; // for문을 빠져나간다.
}
}
}
if(cookie != null) { // “counter”란 이름의 쿠키가 있으면
countNum = Integer.parseInt(cookie.getValue()) + 1; // 값을 정수로 변환한 다음 1 증가한 후
countStr = Integer.toString(countNum); / 다시 증가된 값을 문자열로 변환한 후
cookie.setValue(countStr); // “counter”란 이름의 쿠키값을 새롭게 설정한다.
}
else { // “counter”란 이름의 쿠키가 없으면
cookie = new Cookie(“counter”, “1”); // counter란 이름으로 초기값 1인 쿠키를 생성한다.
}
response.addCookie(cookie); // “counter”란 이름의 쿠키와 그 값을 클라이언트에 전달한다.
%>
<h2>당신은 <%=cookie.getValue()%>
번째 방문하셨습니다.</h2>
</body>
</html>
pageEncoding=”EUC-KR”%>
<!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>
<%
Integer countNum =(Integer)session.getAttribute(“counter”);
// “counter” 이름의 세션값을 저장한다.
{
countNum = new Integer(1); // 초기값으로 1을 저장하고
}
else // “counter”란 이름의 세션값이 있으면
{
int num = countNum.intValue(); // 그 값을 정수로 변환한 후
num++; // 그 값을 하나 증가시킨 후
countNum = new Integer(num); // 증가된 값으로 저장한다.
}
session.setAttribute(“counter”, countNum);
// 새롭게 지정된 값을 “counter”란 이름과 함께 저장한다.
<h2>당신은 <%=countNum.intValue()%>
번째 방문하셨습니다.</h2>
세션ID : <%= session.getId() %>
</body>
</html>