ASP 쿠키
쿠키는 사용자를 인식하는 데 자주 사용됩니다.
예제
- 웰컴 쿠키
- 웰컴 쿠키를 어떻게 생성하나요.
쿠키는 무엇인가요?
쿠키는 사용자를 인식하는 데 자주 사용됩니다. 쿠키는 서버가 사용자 컴퓨터에 남겨둔 작은 파일입니다. 같은 컴퓨터가 브라우저를 통해 페이지를 요청할 때마다, 이 컴퓨터는 쿠키도 보내집니다. ASP를 통해 쿠키 값을 생성하고 가져올 수 있습니다.
쿠키를 어떻게 생성하나요?
"Response.Cookies" 명령은 쿠키를 생성하는 데 사용됩니다.
주의:Response.Cookies 명령은 <html> 태그 앞에 위치해야 합니다.
아래의 예제에서 "firstname" 이름의 쿠키를 생성하고 "Alex" 값을 할당하겠습니다:
<% Response.Cookies("firstname")="Alex" %>
쿠키에 속성을 할당도 가능합니다. 예를 들어, 쿠키의 만료 시간을 설정할 수 있습니다:
<% Response.Cookies("firstname")="Alex" Response.Cookies("firstname").Expires=#May 10,2020# %>
쿠키의 값을 어떻게 가져오나요?
"Request.Cookies" 명령은 쿠키의 값을 가져오기 위해 사용됩니다.
아래의 예제에서 "firstname" 이름의 쿠키의 값을 가져와서 페이지에 표시했습니다:
<% fname=Request.Cookies("firstname") response.write("Firstname=" & fname) %>
출력:
Firstname=Alex
키가 있는 쿠키
쿠키가 여러 값을 가진 집합을 포함하고 있을 때, 쿠키가 키를 가지고 있다고 말할 수 있습니다.
아래의 예제에서 "user" 이름의 쿠키 집합을 생성하겠습니다. "user" 쿠키는 사용자 정보를 포함하는 키를 가집니다:
<% Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Adams" Response.Cookies("user")("country")="UK" Response.Cookies("user")("age")="25" %>
모든 쿠키를 읽기
아래의 코드를 읽어 주세요:
<% Response.Cookies("firstname")="Alex" Response.Cookies("user")("firstname")="John" Response.Cookies("user")("lastname")="Adams" Response.Cookies("user")("country")="UK" Response.Cookies("user")("age")="25" %>
서버가 모든 이러한 쿠키를 사용자에게 전달한 경우를 가정해 보겠습니다.
지금, 우리는 이러한 쿠키를 읽어야 합니다. 아래의 예제에서 이를 어떻게 할 수 있는지 보여드리겠습니다. (주의: 아래의 코드는 쿠키가 키를 가지고 있는지 확인하는 HasKeys를 사용합니다):
<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>
출력:
firstname=Alex user:firstname=John user:lastname=Adams user:country=UK user:age=25
cookie를 지원하지 않는 브라우저에 대한 대응 방법은 무엇인가요?
cookie를 지원하지 않는 브라우저와 상호작용해야 하는 애플리케이션이 있다면, 애플리케이션의 페이지 간에 정보를 전달하는 다른 방법을 사용해야 합니다. 여기서는 두 가지 방법이 있습니다:
1. URL에 매개변수 추가
URL에 매개변수를 추가할 수 있습니다:
<a href="welcome.asp?fname=John&lname=Adams"> 웰컴 페이지로 이동 </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>") %>