ASPCookie _
Cookieは、ユーザーを識別するためによく使用されます。
その他の例
の作成方法。
クッキーとは何ですか?
Cookieは、ユーザーを識別するためによく使用されます。Cookieは、サーバーがユーザーのコンピューターに埋め込む小さなファイルです。同じコンピュータがブラウザでページを要求するたびに、Cookieも送信します。ASPを使用すると、Cookie値の作成と取得の両方を行うことができます。
クッキーを作成する方法は?
「Response.Cookies」コマンドはCookieを作成するために使用されます。
注: Response.Cookiesコマンドは、<html>タグの前に表示する必要があります。
以下の例では、「firstname」という名前のCookieを作成し、それに値「Alex」を割り当てます。
<%
Response.Cookies("firstname")="Alex"
%>
Cookieの有効期限が切れる日付を設定するなど、Cookieにプロパティを割り当てることもできます。
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("firstname").Expires=#May 10,2012#
%>
Cookieの値を取得する方法は?
「Request.Cookies」コマンドは、Cookie値を取得するために使用されます。
以下の例では、「firstname」という名前のCookieの値を取得し、それをページに表示します。
<%
fname=Request.Cookies("firstname")
response.write("Firstname=" & fname)
%>
出力: Firstname = Alex
キー付きのクッキー
Cookieに複数の値のコレクションが含まれている場合、Cookieにはキーがあると言います。
以下の例では、「user」という名前のCookieコレクションを作成します。「ユーザー」Cookieには、ユーザーに関する情報を含むキーがあります。
<%
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
すべてのCookieを読む
次のコードを見てください。
<%
Response.Cookies("firstname")="Alex"
Response.Cookies("user")("firstname")="John"
Response.Cookies("user")("lastname")="Smith"
Response.Cookies("user")("country")="Norway"
Response.Cookies("user")("age")="25"
%>
サーバーが上記のすべてのCookieをユーザーに送信したと想定します。
次に、ユーザーに送信されたすべてのCookieを読み取ります。以下の例は、その方法を示しています(以下のコードは、CookieにHasKeysプロパティを持つKeysがあるかどうかをチェックすることに注意してください)。
<!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>
出力:
名=アレックス
user:firstname = John
user:lastname = Smith
user:country = Norway
user:age = 25
ブラウザがCookieをサポートしていない場合はどうなりますか?
アプリケーションがCookieをサポートしていないブラウザを扱う場合は、他の方法を使用して、アプリケーション内のあるページから別のページに情報を渡す必要があります。これを行うには2つの方法があります。
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>")
%>