ASP 쿠키


쿠키는 종종 사용자를 식별하는 데 사용됩니다.


더 많은 예


를 만드는 방법.


쿠키란?

쿠키는 종종 사용자를 식별하는 데 사용됩니다. 쿠키는 서버가 사용자의 컴퓨터에 삽입하는 작은 파일입니다. 동일한 컴퓨터가 브라우저로 페이지를 요청할 때마다 쿠키도 보냅니다. ASP를 사용하면 쿠키 값을 만들고 검색할 수 있습니다.


쿠키를 만드는 방법?

"Response.Cookies" 명령은 쿠키를 생성하는 데 사용됩니다.

참고: Response.Cookies 명령은 <html> 태그 앞에 나타나야 합니다.

아래 예에서는 "firstname"이라는 이름의 쿠키를 만들고 "Alex" 값을 할당합니다.

<%
Response.Cookies("firstname")="Alex"
%>

쿠키가 만료되어야 하는 날짜를 설정하는 것과 같이 쿠키에 속성을 할당하는 것도 가능합니다.

<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2012#
%>

쿠키 값을 검색하는 방법?

"Request.Cookies" 명령은 쿠키 값을 검색하는 데 사용됩니다.

아래 예에서는 "firstname"이라는 쿠키의 값을 검색하여 페이지에 표시합니다.

<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>

출력: 이름=Alex



열쇠가 있는 쿠키

쿠키에 여러 값의 컬렉션이 포함되어 있으면 쿠키에 키가 있다고 말합니다.

아래 예에서는 "user"라는 쿠키 컬렉션을 만듭니다. "사용자" 쿠키에는 사용자에 대한 정보가 포함된 키가 있습니다.

<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

모든 쿠키 읽기

다음 코드를 보십시오.

<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>

귀하의 서버가 위의 모든 쿠키를 사용자에게 보냈다고 가정합니다.

이제 사용자에게 전송된 모든 쿠키를 읽고 싶습니다. 아래 예제는 이를 수행하는 방법을 보여줍니다(아래 코드는 쿠키에 HasKeys 속성이 있는 키가 있는지 확인합니다).

<!DOCTYPE html>
<html>
<body>

<%
dim x,y
for each x in Request.Cookies
  response.write("<p>")
  if Request.Cookies(x).HasKeys then
    for each y in Request.Cookies(x)
      response.write(x & ":" & y & "=" & Request.Cookies(x)(y))
      response.write("<br>")
    next
  else
    Response.Write(x & "=" & Request.Cookies(x) & "<br>")
  end if
  response.write "</p>"
next
%>

</body>
</html>

산출:

이름=알렉스

사용자:이름=John
사용자:성=Smith
사용자:country=노르웨이
사용자:나이=25


브라우저가 쿠키를 지원하지 않으면 어떻게 됩니까?

응용 프로그램이 쿠키를 지원하지 않는 브라우저를 다루는 경우 응용 프로그램의 한 페이지에서 다른 페이지로 정보를 전달하기 위해 다른 방법을 사용해야 합니다. 두 가지 방법이 있습니다.

1. URL에 매개변수 추가

URL에 매개변수를 추가할 수 있습니다.

<a href="welcome.asp?fname=John&lname=Smith">Go to Welcome Page</a>

다음과 같이 "welcome.asp" 파일에서 값을 검색합니다.

<%
fname=Request.querystring("fname")
lname=Request.querystring("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>

2. 양식 사용

양식을 사용할 수 있습니다. 사용자가 제출 버튼을 클릭하면 양식은 사용자 입력을 "welcome.asp"로 전달합니다.

<form method="post" action="welcome.asp">
First Name: <input type="text" name="fname" value="">
Last Name: <input type="text" name="lname" value="">
<input type="submit" value="Submit">
</form>

다음과 같이 "welcome.asp" 파일에서 값을 검색합니다.

<%
fname=Request.form("fname")
lname=Request.form("lname")
response.write("<p>Hello " & fname & " " & lname & "!</p>")
response.write("<p>Welcome to my Web site!</p>")
%>