모듈 1: ASP 페이지 만들기

모듈 1에서는 HTML과 Microsoft® Visual Basic® Scripting Edition(VBScript)을 사용하여 ASP 페이지(.asp 파일)를 만듭니다. 이 모듈은 다음 학습 내용을 포함합니다.


단원 1:ASP 페이지 쓰기

ASP를 배우는 가장 좋은 방법은 예제를 보고 궁금한 정수 값, 문자열 및 문을 변경하고 브라우저에서 일어나는 변경 사항을 확인하는 것입니다.

이 단원에서는 다음 작업을 수행합니다.

ASP 페이지에서 사용하는 기본 스크립트 언어는 VBScript입니다. 그러나 구분 기호는 Jscript에서와 같습니다. 다음과 같이 꺾쇠 괄호를 구분 기호로 사용하여 .htm 페이지처럼 HTML 태그를 둘러쌉니다.

  <example></example>

다음과 같이 백분율 기호화 대괄호를 구분 기호로 사용하여 스크립트 코드를 둘러쌉니다.

  <% example %>

 

다음과 같이 한 쌍의 스크립트 구분 기호 안에 많은 스크립트 문을 삽입할 수 있습니다.

  <font face="MS Gothic">
  <%
   'Create a variable.
   dim strGreeting

   'Set the greeting. strGreeting = "안녕하세요?"

   'Print out the greeting, using the ASP Response object.
   Response.Write strGreeting & "<BR>"

   'Also print out the greeting using the <%= method.
  %>
  <%=strGreeting%>
  </font>

 

이 코드는 브라우저에 다음 내용을 표시합니다.

안녕하십니까?
안녕하십니까?

 

Jscript를 사용하여 앞의 예제를 나타냅니다.

  <%@ Language=JScript %>

  <font face="MS Gothic">
  <%
   //Create a variable.
   var strGreeting;

   //Set the greeting.
   strGreeting = "안녕하십니까!";

   //Print out the greeting, using the ASP Response object.
   Response.Write(strGreeting + "<BR>");

   //Also print out the greeting using the <%= method.
  %>
  <%=strGreeting%>
  </font>

ASP 페이지를 만들려면 메모장과 같은 텍스트 편집기를 사용하여 .htm 대신 .asp 확장명으로 페이지를 저장합니다. .asp 파일 확장명을 사용하면 페이지를 클라이언트에게 보내기 전에 IIS가 ASP 엔진을 통해 페이지를 보냅니다. (참고: 메모장의 다른 이름으로 저장 대화 상자에서 파일 형식 상자의 텍스트 문서(*.txt)를 선택하면 메모장은 파일 이름에 자동으로 .txt를 추가합니다. 확장명을 자동으로 추가하지 않으려면 다른 이름으로 저장 상자에서 모든 파일을 선택하고 파일 이름 필드에 MyFile.asp와 같이 전체 파일 이름을 입력한 다음 저장을 클릭합니다. )


예제 1

이 예제는 인사말, 날짜, 현재 시간을 표시합니다. 이 예제를 실행하려면 다음 코드를 복사하여 빈 파일에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 Example1.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/Example1.asp를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Example 1</title>
  </head>
  <body>
  <font face="MS Gothic">

  <H1>Welcome to my Home Page</H1>
  <%
   'Create some variables.
   dim strDynamicDate
   dim strDynamicTime

   'Get the date and time.
   strDynamicDate = Date()
   strDynamicTime = Time()

   'Print out a greeting, depending on the time, by comparing the last 2 characters in strDymamicTime to "PM".
   If "PM" = Right(strDynamicTime, 2) Then
      Response.Write "<H3>Good Afternoon!</H3>"
   Else
      Response.Write "<H3>Good Morning!</H3>"
   End If
  %>
  Today's date is <%=strDynamicDate%> and the time is <%=strDynamicTime%> 

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다. 날짜나 시간은 상황에 맞게 달라질 수 있습니다.

 Welcome to my Home Page

  Good Afternoon!

  Today's date is 10/20/2000 and the time is 7:29:50 PM


참고: 웹 서버가 다음 순서에 따라 Example1.asp를 처리합니다.

  1. <%@ Language=VBScript %>는 ASP 엔진이 스크립트 코드를 변환할 때 VBScript 엔진을 사용하도록 합니다.
  2. ASP 엔진이 HTML 코드 블록을 무시합니다.
  3. ASP 엔진이 <%...%> 블록의 코드를 실행하고 자리 표시자가 있는 블록을 대체합니다. Response.Write 문자열과 <%=...%> 문자열의 결과가 서버 메모리에 저장됩니다.
  4. 페이지가 ASP 엔진을 벗어나기 전에, 일치하는 자리 표시자가 있으면 Response.Write 문자열과 <%=...%> 문자열의 결과가 HTML 코드에 삽입됩니다.
  5. 전체 페이지가 HTML 코드 페이지가 되어 ASP 엔진을 벗어나고 서버가 클라이언트에게 페이지를 보냅니다.

예제 2

이 예제는 ASP 페이지에 For...Next 루프를 포함시켜 다소 동적인 논리를 추가합니다. For...Next 루프는 사용할 수 있는 6개 조건문 중의 하나입니다. 나머지는 Do...Loop, For Each...Next, If...Then...Else...End If, Select..Case...End Select, While...Wend입니다. 이러한 문에 대해서는 VBScript 아래의 Windows 스크립트 기술을 참조하십시오.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 파일을 Example2.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/Example2.asp 를 입력하여 브라우저에서 예제를 봅니다.

처리 순서는 Example1.asp에서와 같습니다.

  <%@ Language=VBScript %> 

  <html>
  <head>
  <title>Example 2</title>
  </head>
  <body>
  <font face="MS Gothic">

  <%
   'Create a variable.
   dim strTemp
   dim font1, font2, font3, font, size

   'Set the variable.
   strTemp= "BUY MY PRODUCT!"
   fontsize = 0

   'Print out the string 5 times using the For...Next loop.
   For i = 1 to 5

     'Close the script delimiters to allow the use of HTML code and <%=...
     %>.
     <table align=center><font size= <%=fontsize%>> <%=strTemp%> </font></table>
     <%
     fontsize = fontsize + i

   Next

  %>
  <table align=center><font size=6><B> IT ROCKS! <B></font></table><BR>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

BUY MY PRODUCT!
BUY MY PRODUCT!
BUY MY PRODUCT!
BUY MY PRODUCT!
BUY MY PRODUCT!
IT ROCKS!

 

Jscript를 사용하여 예제 2를 나타냅니다.

  <%@ Language=JScript %>

  <html>
  <head>
  <title>Example 2</title>
  </head>
  <body>
  <font face="MS Gothic">

  <%
  //Create a variable.
  var strTemp;
  var font1, font2, font3, font, size;

  //Set the variable.
  strTemp= "BUY MY PRODUCT!";
  fontsize = 0;

  //Print out the string 5 times using the For...Next loop.
  for (i = 1; i < 6; i++) {

  //Close the script delimiters to allow the use of HTML code and <%=...
  %>.
  <table align=center><font size= <%=fontsize%>> <%=strTemp%> </font></table>
  <%
  fontsize = fontsize + i;

  }

  %>
  <table align=center><font size=6><B> IT ROCKS! <B></font></table><BR>

  </font>
  </body>
  </html>

예제 3

많은 사업가들이 세계 시장을 겨냥하여 여러 언어를 지원하는 웹 사이트를 만들고 있습니다. 사용자의 로케일에 맞게 날짜, 시간, 통화 형식을 지정하는 것이 좋습니다.

예제 3에서는 ASP 페이지에서 미리 정의한 함수가 날짜와 통화를 표시합니다. GetLocale 함수, SetLocale 함수, FormatCurrency 함수, FormatDateTime 함수를 사용하여 다양한 로케일에 맞는 날짜와 통화 형식을 지정합니다. 로케일 ID 문자열은 MSDN의 Locale ID Chart에 있습니다. 이 예제에서는 비유럽 문자와 유럽 운영 체제를 표시하는 코드 페이지를 다루지 않습니다. 자세한 내용은 IIS 설명서의 코드 페이지 항목을 참조하십시오.

참고: VBScript에는 90개 이상의 미리 정의된 함수가 있으며 Windows 스크립트 기술에 자세히 정의되어 있습니다. VBScript, 설명서, 언어 참고, 함수를 차례로 선택하여 설명서를 참조하십시오.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 Example3.asp로 파일을 저장합니다. 주소 표시줄에 http://localhost/Tutorial/Example3.asp 를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Example 3</title>
  </head>
  <body>
  <font face="MS Gothic">

  <H3>Thank you for your purchase.  Please print this page for your records.</H3>
  <%
   'Create some variable.
   dim saveLocale
   dim totalBill

   'Set the variables.
   saveLocale = GetLocale
   totalBill = CCur(85.50)

   'For each of the Locales, format the date and the currency
   SetLocale("fr")
   Response.Write"<B>Formatted for French:</B><BR>"
   Response.Write FormatDateTime(Date, 1) & "<BR>"
   Response.Write FormatCurrency(totalBill) & "<BR>"
   SetLocale("de")
   Response.Write"<B>Formatted for German:</B><BR>"
   Response.Write FormatDateTime(Date, 1) & "<BR>"
   Response.Write FormatCurrency(totalBill) & "<BR>"
   SetLocale("en-au")
   Response.Write"<B>Formatted for English - Australia:</B><BR>"
   Response.Write FormatDateTime(Date, 1)& "<BR>"
   Response.Write FormatCurrency(totalBill) & "<BR>"

   'Restore the original Locale
   SetLocale(saveLocale)
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

Thank you for your purchase. Please print this page for your records.

  Formatted for French:
  vendredi 20 octobre 2000
  85,50 F
  Formatted for German:
  Freitag, 20. Oktober 2000
  85,50 DM
  Formatted for English - Australia:
  Friday, 20 October 2000
  $85.50

예제 4

ASP 스크립트에서는 문자열을 조작하는 함수를 가장 많이 사용합니다. 가장 강력한 문자열 함수는 정규 표현식을 사용합니다. 정규 표현식은 적용하기 어려우므로 예제 4에서는 문자열 식과 정규 표현식을 사용하여 문자를 대체하는 방법을 설명합니다. 정규 표현식은 Windows 스크립트 기술에 정의되어 있습니다.   VBScript, 설명서, 정규 표현식 가이드를 차례로 선택하여 설명서를 참조하십시오.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 Example4.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/Example4.asp 를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Example 4</title>
  </head>
  <body>
  <font face="MS Gothic">

  <H3>Changing a Customer's Street Address</H3>
  <%
   'Create some variables.
   dim strString
   dim strSearchFor     ' as a string
   dim reSearchFor     ' as a regular expression
   dim strReplaceWith

   'Set the variables.
   strString = "Jane Doe<BR>100 Orange Road<BR>Orangeville, WA<BR>98100<BR>800.555.1212<BR>"
   '   Using a string object
   strSearchFor = "100 Orange Road<BR>Orangeville, WA<BR>98100"
   '   Using a regular expression object
   Set reSearchFor = New RegExp
   reSearchFor.Pattern = "100 Orange Road<BR>Orangeville, WA<BR>98100"
   reSearchFor.IgnoreCase = False

   strReplaceWith = "200 Bluebell Court<BR>Blueville, WA<BR>98200"

   'Verify that strSearchFor exists...
   '   using a string object.
   If Instr(strString, strSearchFor) Then
     Response.Write "strSearchFor was found in strString<BR>"
   Else
     Response.Write "Fail"
   End If
   '   using a regular expression object.
   If reSearchFor.Test(strString) Then
     Response.Write "reSearchFor.Pattern was found in strString<BR>"
   Else
     Response.Write "Fail"
   End If

   'Replace the string...
   Response.Write "<BR>Original String:<BR>" & strString & "<BR>"
   '   using a string object.
   Response.Write "String where strSearchFor is replaced:<BR>"
   Response.Write Replace(strString, strSearchFor, strReplaceWith) & "<BR>"
   '   using a regular expression object.
   Response.Write "String where reSearchFor is replaced:<BR>"
   Response.Write reSearchFor.Replace(strString, strReplaceWith) & "<BR>"
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

 Changing a Customer's Street Address

  strSearchFor was found in strString
  reSearchFor.Pattern was found in strString

  Original String:
  Jane Doe
  100 Orange Road
  Orangeville, WA
  98100
  800.555.1212

  String where strSearchFor is replaced:
  Jane Doe
  200 Bluebell Court
  Blueville, WA
  98200
  800.555.1212

  String where reSearchFor is replaced:
  Jane Doe
  200 Bluebell Court
  Blueville, WA
  98200
  800.555.1212


단원 2: 폼을 사용하여 정보 제출

인트라넷이나 인터넷 서버 응용 프로그램은 웹 페이지에서 폼을 사용하여 사용자 입력을 받아 들이는 데 자주 쓰입니다. ASP는 Request 개체에 QueryString 컬렉션과 Form 컬렉션을 포함하여 폼 정보를 처리하게 합니다.

이 단원에서는 HTML 폼에 사용자 입력을 받아들여 웹 서버의 동일한 페이지로 다시 보내는 HTML 페이지를 만듭니다. 그런 다음 웹 서버가 사용자 입력을 표시합니다. 나중에 이 모듈에서 폼에 대한 이 정보를 사용하여 ASP 스크립트를 사용하는 방명록 응용 프로그램을 작성합니다. 이 단원을 완료하려면 다음 작업을 수행합니다.

예제 1: 단추

폼에 있는 여러 가지 요소를 사용하여 사용자가 데이터를 입력할 수 있습니다. 이 예제에는 단추라는 다섯 개의 입력 폼이 있습니다. 라디오 단추, 전송 단추, 재설정 단추, 확인란 단추, 텍스트 단추 등 다양한 종류의 단추가 있습니다.

사용자가 폼에 입력한 정보는 웹 응용 프로그램으로 보내져야 합니다.   사용자가 웹 페이지에서 "전송" 단추를 클릭하면 폼 데이터는 클라이언트에서 폼 태그 ACTION 요소에 나열된 웹 페이지로 보내집니다. 이 웹 페이지는 호출 페이지와 같을 필요가 없습니다. 이 예제에서 ACTION 요소에 나열된 웹 페이지는 호출 페이지와 같으므로 다른 페이지를 호출할 필요가 없습니다.

이 예제에서는 METHOD="POST"를 사용하여 웹 클라이언트 브라우저에서 웹 서버로 데이터를 보냅니다. 폼에서 METHOD="POST"를 사용하면 사용자 데이터가 Request 개체의 Form 컬렉션에서 끝납니다.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 Button.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/Button.asp를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Button Form</title>
  </head>
  <body>
  <font face="MS Gothic">

  <FORM NAME="Button Example" METHOD="POST" ACTION="button.asp">
  <H3>Computer Programming Experience:</H3>
  <p>
  <INPUT TYPE="RADIO" NAME= "choice" VALUE="Less than 1"> Less than 1 year.<BR>
  <INPUT TYPE="RADIO" NAME= "choice" VALUE="1 to 5"> 1-5 years.<BR>
  <INPUT TYPE="RADIO" NAME= "choice" VALUE="More than 5"> More than 5 years.<BR>
  </p>
  <p>
  <INPUT TYPE="SUBMIT" VALUE="Submit">
  <INPUT TYPE="RESET" VALUE="Clear Form">
  </p>
  </form>

  <%
   'Check to see if input has already been entered. 
   dim strChoice
   strChoice = Request.Form("choice")

   If "" = strChoice Then
     Response.Write "<P>(No input yet.)</P>"
   Else
     Response.Write "<P>Your last choice was <B>" & strChoice & "</B></P>"
   End If
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

  Computer Programming Experience:

  1 이하
  1-5 years.
  More than 5 years.

 

  (No input yet.)


예제 2: 입력 폼 요소

이 예제에는 텍스트 필드라는 세 가지 입력 폼 요소와 확인란이라는 두 가지 입력 폼 요소가 있습니다. 확인란은 두 개 이상 선택할 수 있다는 점에서 옵션 단추와 다릅니다. 데이터를 서버로 돌려 보내려면 전송 단추가 여전히 필요합니다.

이 예제에서는 METHOD=GET을 사용하여 데이터를 웹 클라이언트 브라우저에서 웹 서버로 보냅니다. 폼에 METHOD=GET을 사용하는 경우 사용자 데이터는 Reset 개체의 QueryString 컬렉션에서 끝납니다.

전송을 클릭한 다음 주소 표시줄의 URL 끝에 QueryString 요소가 표시되어야 합니다.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 Text.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/Text.asp를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %> 

  <html>
  <head>
  <title>Text and Checkbox Form</title>
  </head>
  <body>
  <font face="MS Gothic">

  <FORM NAME="TextCheckbox Example" METHOD="GET" ACTION="text.asp">
  <H3>Please fill out this form to get information on our products:</H3>
  <p>
  <table>
  <tr>
  <td><font face="MS Gothic">Name (required)</td>
  <td><INPUT TYPE="TEXT" NAME="name" VALUE="" SIZE="20" MAXLENGTH="150"></td>
  </tr><tr>
  <td><font face="MS Gothic">Company</td>
  <td><INPUT TYPE="TEXT" NAME="company" VALUE="" SIZE="25" MAXLENGTH="150"></td>
  </tr><tr>
  <td><font face="MS Gothic">E-mail (required)</td>
  <td><INPUT TYPE="TEXT" NAME="email" VALUE="" SIZE="25" MAXLENGTH="150"></td>
  </tr>
  </table>
  </p>
  <p>
  Requesting information on our:<BR>
  <INPUT TYPE="CHECKBOX" NAME= "info" VALUE="software">Software<BR>
  <INPUT TYPE="CHECKBOX" NAME= "info" VALUE="hardware">Hardware <BR>
  </p>
  <p>
  <INPUT TYPE="SUBMIT" VALUE="Submit">
  <INPUT TYPE="RESET" VALUE="Clear Form">
  </p>
  </form>

  <%
   'Check to see if input has already been entered.
   dim strName, strEmail, strCompany, strInfo
   strName = Request.QueryString("name")
   strEmail = Request.QueryString("email")
   strCompany = Request.QueryString("company")
   strInfo = Request.QueryString("info")

   'Display what was entered.
   If ("" = strName) OR ("" = strEmail) Then
     Response.Write "<P>(No required input entered yet.)</P>"
   Else
     Response.Write "<P>Your are " & strName
     If Not ("" = strCompany) Then
       Response.Write " from " & strCompany
     End If
     Response.Write ". <BR>Your email address is " & strEmail
     If Not ("" = strInfo) Then
       Response.Write " and you would like information on " & strInfo & ".</P>"
     End If
   End If
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

  Please fill out this form to get information about our products:

  Name (required)
  Company
  E-mail (required)

  Requesting information about our:
  Software
  Hardware

 

  (No required input entered yet.)


단원 3: 데이터베이스를 사용하여 방명록 만들기

이 단원에서는 시스템에 설치된 Microsoft Access가 있어야 하며 Access가 64비트 플랫폼용으로 개발될 때까지는 64비트 플랫폼에서 지원되지 않습니다.

단원 3에서는 방명록 응용 프로그램을 개발합니다. 웹 사이트를 방문하는 사람은 방명록에 이름, 전자 메일 주소, 메모 등의 정보를 남길 수 있습니다. 이 단원에서는 Access 데이터베이스를 만들어 다음 작업을 수행합니다.


Access 데이터베이스 만들기

GuestBook.mdb라는 Access 데이터베이스를 만들어 x:\Inetpub\Wwwroot\Tutorial에 저장합니다. 데이터베이스에 GuestBook이라는 테이블을 만듭니다. Access에 있는 디자인 보기에서 새 테이블 만들기 옵션을 사용하여 다음 필드와 속성을 추가합니다.

필드 이름 데이터 형식 필드 일반 속성
FID 일련 번호 필드 크기=정수(Long),
새 값=증분,
인덱스=예(중복 불가능)
FTB1 텍스트 필드 크기=255,
필수=아니오,
빈 문자열 허용=예,
인덱스=아니오
FTB2 텍스트 필드 크기=255,
필수=아니오,
빈 문자열 허용=예,
인덱스=아니오
FTB3 텍스트 필드 크기=255,
필수=아니오,
빈 문자열 허용=예,
인덱스=아니오
FTB4 텍스트 필드 크기=255,
필수=아니오,
빈 문자열 허용=예,
인덱스=아니오
FMB1 메모 필수=아니오,
빈 문자열 허용=예

ASP 페이지를 만들어 Access 데이터베이스에 데이터 추가

데이터베이스를 만든 다음 ASP 페이지를 작성하고 Microsoft ActiveX® Data Objects(ADO)를 사용하여 데이터베이스에 연결하고 들어오는 데이터를 읽을 수 있습니다. ADO는 거의 모든 데이터 형식을 조작할 수 있는 메서드와 속성을 가진 개체 모음입니다. 데이터베이스를 자주 사용하는 경우 ADO 프로그래머 참고서를 구입해야 합니다. 다음 예제에서는 데이터베이스를 열고 데이터베이스에서 읽고 쓸 수 있는 가장 기본적인 ADO 코드에 대해서만 설명합니다.

다음 두 예제의 결과는 동일하지만 첫 번째 예제에서는 Connection 개체만 사용하고 두 번째 예제에서는 보다 강력한 Command 개체를 사용합니다. 두 예제를 비교하여 개체가 어떻게 연결되는지 확인하십시오. 이 개체에 익숙해지면 ADO 프로그래머 참고서에서 더 많은 메서드와 속성을 사용해 보십시오.

ASP 페이지의 ADO 오류에 대한 예제를 보려면 연결 문자열에 잘못된 내용을 입력하거나 데이터베이스를 읽기 전용으로 설정한 다음 데이터베이스의 이름을 바꾸고 페이지를 탐색합니다.


예제 1: ADO Connection 개체만 사용

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 GuestBook1.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/GuestBook1.asp 를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Guest Book Using Connection Object Only</title>
  </head>
  <body>
  <font face="MS Gothic">
  <h2>Guest Book Using Connection Object Only</h2>

  <%
   If Not Request.QueryString("Message") = "True" Then
     'No information has been input yet, so provide the form.
  %>
     <p>
     <FORM NAME="GuestBook1" METHOD="GET" ACTION="guestbook1.asp">
     <table>
       <tr>
       <td><font face="MS Gothic">From:</td><td><INPUT TYPE="TEXT" NAME="From"></td>
       </tr><tr>
       <td><font face="MS Gothic">E-mail Address:</td><td><INPUT TYPE="TEXT" NAME="EmailAdd"></td>
       </tr><tr>
       <td><font face="MS Gothic">CC:</td><td><INPUT TYPE="TEXT" NAME="CC"></td>
       </tr><tr>
       <td><font face="MS Gothic">Subject:</td><td><INPUT TYPE="TEXT" NAME="Subject"></td>
       </tr>
     </table>
     Message:<br><TEXTAREA NAME="Memo" ROWS=6 COLS=70></TEXTAREA>
     </p>

     <p>
     <INPUT TYPE="HIDDEN" NAME="Message" VALUE="True">
     <INPUT TYPE="SUBMIT" VALUE="Submit Information">
     </FORM>
     </p>
  <%
   Else
     'The HIDDEN button above sets the Message variable to True.
     'We know now that form data has been entered.

     'Get the data from the form. We will be inserting it into the database.
     'Access doesn't like some characters, such as single-quotes, so encode the
     ' data using the HTMLEncode method of the ASP Server object.
     dim strTB1, strTB2, strTB3, strTB4, strMB1, strCommand
     strTB1 = Server.HTMLEncode(Request.QueryString("From"))
     strTB2 = Server.HTMLEncode(Request.QueryString("EMailAdd"))
     strTB3 = Server.HTMLEncode(Request.QueryString("CC"))
     strTB4 = Server.HTMLEncode(Request.QueryString("Subject"))
     strMB1 = Server.HTMLEncode(Request.QueryString("Memo"))

     'This is a connection string. ADO uses it to connect to a database through the Access driver.
     'It needs the provider name of the Access driver and the name of the Access database.
     'Connection strings are slightly different, depending on the provider being used,
     ' but they all use semicolons to separate variables.
     'If this line causes and error, search in your registry for
     ' Microsoft.JET to see if 4.0 is your version.
     strProvider = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\InetPub\Wwwroot\Tutorial\guestbook.mdb;"

     'This creates an instance of an ADO Connection object.
     'There are 4 other ADO objects available to you, each with different methods and
     'properties that allow you to do almost anything with database data.
     Set objConn = server.createobject("ADODB.Connection")

     'The Open method of the Connection object uses the connection string to
     ' create a connection to the database.
     objConn.Open strProvider

     'Define the query.
     'There are many types of queries, allowing you to add, remove, or get data.
     'This query will add your data into the database, using the INSERT INTO key words.
     'Here, GuestBook is the name of the table.
     'You need single-quotes around strings here.
     strCommand = "INSERT INTO GuestBook (FTB1,FTB2,FTB3,FTB4,FMB1) VALUES ('"
     strCommand = strCommand & strTB1 & "','" & strTB2 & "','" & strTB3 & "','" & strTB4 & "','" & strMB1
     strCommand = strCommand & "')"

     'Execute the query to add the data to the database.
     objConn.Execute strCommand

     Response.Write("Thank you! Your data has been added.")

     End If
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

  Guest Book Using Connection Object Only

  From:
  E-mail Address:
  CC:
Subject
Message

 


예제 2: Connection 개체와 Command 개체를 함께 사용

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 GuestBook2.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/GuestBook2.asp 를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Guest Book Using Connection Object and Command Object</title>
  </head>
  <body>
  <font face="MS Gothic">
  <h2>Guest Book Using Connection Object and Command Object</h2>

  <%
   If Not Request.QueryString("Message") = "True" Then
     'No information has been input yet, so provide the form.
  %>
     <p>
     <FORM NAME="GuestBook2" METHOD="GET" ACTION="guestbook2.asp">
     <table>
       <tr>
       <td><font face="MS Gothic">From:</td><td><INPUT TYPE="TEXT" NAME="From"></td>
       </tr><tr>
       <td><font face="MS Gothic">E-mail Address:</td><td><INPUT TYPE="TEXT" NAME="EmailAdd"></td>
       </tr><tr>
       <td><font face="MS Gothic">CC:</td><td><INPUT TYPE="TEXT" NAME="CC"></td>
       </tr><tr>
       <td><font face="MS Gothic">Subject:</td><td><INPUT TYPE="TEXT" NAME="Subject"></td>
       </tr>
     </table>
     Message:<br><TEXTAREA NAME="Memo" ROWS=6 COLS=70></TEXTAREA>
     </p>

     <p>
     <INPUT TYPE="HIDDEN" NAME="Message" VALUE="True">
     <INPUT TYPE="SUBMIT" VALUE="Submit Information">
     </FORM>
     </p>
  <%
   Else
     'The HIDDEN button above sets the Message variable to True.
     'We know now that form data has been entered.

     'Get the data from the form. We will be inserting it into the database.
     'Access doesn't like some characters, such as single-quotes, so encode the
     ' data using the HTMLEncode method of the ASP Server object.
     dim strTB1, strTB2, strTB3, strTB4, strMB1
     strTB1 = Server.HTMLEncode(Request.QueryString("From"))
     strTB2 = Server.HTMLEncode(Request.QueryString("EMailAdd"))
     strTB3 = Server.HTMLEncode(Request.QueryString("CC"))
     strTB4 = Server.HTMLEncode(Request.QueryString("Subject"))
     strMB1 = Server.HTMLEncode(Request.QueryString("Memo"))

     'The Memo data type in the Access database allows you to set the field size.
     If strMB1 = "" Then
       iLenMB1 = 255
     Else
       iLenMB1 = Len(strMB1)
     End If

     'This is a connection string. ADO uses it to connect to a database through the Access driver.
     'It needs the provider name of the Access driver and the name of the Access database.
     'Connection strings are slightly different, depending on the provider being used,
     ' but they all use semicolons to separate variables.
     'If this line causes and error, search in your registry for
     ' Microsoft.JET to see if 4.0 is your version.
     strProvider = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\InetPub\Wwwroot\Tutorial\guestbook.mdb;"

     'This creates an instance of an ADO Connection object.
     'There are 4 other ADO objects available to you, each with different methods and
     'properties that allow you to do almost anything with database data.
     Set objConn = server.createobject("ADODB.Connection")

     'The Open method of the Connection object uses the connection string to
     ' create a connection to the database.
     objConn.Open strProvider

     'This creates an instance of an ADO Command object.
     'Although you could do most of your work with the Connection object,
     ' the Command object gives you more control.
     Set cm = Server.CreateObject("ADODB.Command")

     'The ActiveConnection property allows you to attach to an Open connection.
     'This is how you link the Connection object above to the Command object.
     cm.ActiveConnection = objConn

     'Define the query.
     'There are many types of queries, allowing you to add, remove, or get data.
     'This query will add your data into the database, using the INSERT INTO keywords.
     'Because we are using the Command object, we need to put our query into the
     ' CommandText property.
     'Here, GuestBook is the name of the table.
     cm.CommandText = "INSERT INTO GuestBook (FTB1,FTB2,FTB3,FTB4,FMB1) VALUES (?,?,?,?,?)"

     'This is where you see the power of the Command object.
     'By putting ? marks in the string above, we can use the Parameters collection
     ' to have ADO fill in the ? with the detailed parameters below.
     'cm.CreateParameter formats the parameter for you.
     'cm.Parameters.Append appends the parameter to the collection.
     'Make sure they are in the same order as (TB1,TB2,TB3,TB4,MB1).

     Set objparam = cm.CreateParameter(, 200, , 255, strTB1)
     cm.Parameters.Append objparam

     Set objparam = cm.CreateParameter(, 200, , 255, strTB2)
     cm.Parameters.Append objparam

     Set objparam = cm.CreateParameter(, 200, , 255, strTB3)
     cm.Parameters.Append objparam

     Set objparam = cm.CreateParameter(, 200, , 255, strTB4)
     cm.Parameters.Append objparam

     Set objparam = cm.CreateParameter(, 201, , iLenMB1, strMB1)
     cm.Parameters.Append objparam

     'Execute the query to add the data to the database.
     'Here, the Execute method of the Command object is called instead of
     ' the Execute method of the Connection object.
     cm.Execute

     Response.Write("Thank you! Your data has been added.")

     End If
  %>

  </font>
  </body>
  </html>

다음과 같이 브라우저에 GuestBook1.asp와 같은 내용이 표시되어야 합니다.

  Guest Book Using Connection Object Only

  From:
  E-mail Address:
  CC:
Subject
Message

 


예제 3: 브라우저에 데이터베이스 표시

데이터베이스에 정보를 입력한 다음 다른 스크립트를 포함하고 있는 웹 페이지를 사용하여 데이터를 보고 편집할 수 있습니다. 쿼리를 정의한 방식을 사용하지 않고 ADO 코드를 약간만 변경합니다.
마지막 두 예제에서 INSERT INTO 쿼리를 사용하여 데이터베이스에 레코드를 추가했습니다. 이 예제에서는 SELECT 쿼리를 사용하여 데이터베이스에서 레코드를 선택하고 브라우저에 표시합니다. 또한 DELETE 쿼리를 사용하여 데이터베이스의 레코드를 제거합니다. 이 예제에서 사용하지 않는 유일한 쿼리는 UPDATE 쿼리로서 INSERT INTO 쿼리와 구문이 같습니다. UPDATE 쿼리를 사용하여 데이터베이스의 필드를 변경할 수 있습니다.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 ViewGB.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/ViewGB.asp를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>View Guest Book</title>
  </head>
  <body>
  <font face="MS Gothic">
  <h2>View Guest Book</h2>

  <%
  'Read in any user input. Any of these can be empty.
  'By doing this first, we can preserve the user input in the form.
  dim strTB1, strTB2, strTB3, strTB4, strMB1, strSort, iDelete
  strTB1 = Server.HTMLEncode(Request.QueryString("From"))
  strTB2 = Server.HTMLEncode(Request.QueryString("EMailAdd"))
  strTB3 = Server.HTMLEncode(Request.QueryString("CC"))
  strTB4 = Server.HTMLEncode(Request.QueryString("Subject"))
  strMB1 = Server.HTMLEncode(Request.QueryString("Memo"))
  strSort = Server.HTMLEncode(Request.QueryString("sort"))
  iDelete = CInt(Request.QueryString("Delete"))

  'Because we use this variable, and it might not be set...
  If "" = strSort Then
    strSort = "FID"
  End If
  %>

  <p>
  <FORM NAME="ViewGuestBook" METHOD="GET" ACTION="viewgb.asp">
  <table>
    <tr>
    <td><font face="MS Gothic">Sort by which column:</td>
    <td><SELECT NAME="sort" SIZE="1">
      <OPTION VALUE="FID">ID Number</OPTION>
      <OPTION VALUE="FTB1">Name</OPTION>
      <OPTION VALUE="FTB2">Email</OPTION>
      <OPTION VALUE="FTB3">CC</OPTION>
      <OPTION VALUE="FTB4">Subject</OPTION>
      <OPTION VALUE="FMB1">Memo</OPTION>
    </SELECT></td>
    </tr><tr>
    <td><font face="MS Gothic">Name Contains:</td>
    <td><INPUT TYPE="TEXT" NAME="From" VALUE="<%=strTB1%>"></td>
    </tr><tr>
    <td><font face="MS Gothic">E-mail Address Contains:</td>
    <td><INPUT TYPE="TEXT" NAME="EmailAdd" VALUE="<%=strTB2%>"></td>
    </tr><tr>
    <td><font face="MS Gothic">CC Contains:</td>
    <td><INPUT TYPE="TEXT" NAME="CC" VALUE="<%=strTB3%>"></td>
    </tr><tr>
    <td><font face="MS Gothic">Subject Contains:</td>
    <td><INPUT TYPE="TEXT" NAME="Subject" VALUE="<%=strTB4%>"></td>
    </tr><tr>
    <td><font face="MS Gothic">Memo Contains:</td>
    <td><INPUT TYPE="TEXT" NAME="Memo" VALUE="<%=strMB1%>"></td>
    </tr>
  </table>
  <INPUT TYPE="SUBMIT" VALUE="Submit Search Parameters">
  </p>

  <%
  'Create your connection string, create an instance of the Connection object,
  ' and connect to the database.
  strProvider = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=C:\InetPub\Wwwroot\Tutorial\guestbook.mdb;"
  Set objConn = Server.CreateObject("ADODB.Connection")
  objConn.Open strProvider

  'Define the query.
  If iDelete = 0 Then
    'If the Delete variable is not set, the query is a SELECT query.
    '* means all fields. ASC means ASCII. % is a wildcard character.
    strQuery = "SELECT * FROM GuestBook"
    strQuery = strQuery & " WHERE FTB1 LIKE '%" & strTB1 & "%'"
    strQuery = strQuery & " AND FTB2 LIKE '%" & strTB2 & "%'"
    strQuery = strQuery & " AND FTB3 LIKE '%" & strTB3 & "%'"
    strQuery = strQuery & " AND FTB4 LIKE '%" & strTB4 & "%'"
    strQuery = strQuery & " AND FMB1 LIKE '%" & strMB1 & "%'"
    strQuery = strQuery & " ORDER BY " & StrSort & " ASC"
  Else
    'We want to delete a record.
    strQuery = "DELETE FROM GuestBook WHERE FID=" & iDelete
  End If

  'Executing the SELECT query creates an ADO Recordset object.
  'This holds the data you get from the database.
  Set objRS = objConn.Execute(strQuery)

  'Now that you have the database data stored in the Recordset object,
  ' show it in a table.
 %>

  <p>
  <FORM NAME="EditGuestBook" METHOD="GET" ACTION="viewgb.asp">
  <table border=1 cellpadding=4 >
  <%
    On Error Resume Next

    If objRS.EOF Then
      If iDelete = 0 Then
        Response.Write "<tr><td><font face=&quot;MS Gothic&quot;>There are no entries in the database.</font></td></tr>"
      Else
        Response.Write "<tr><td><font face=&quot;MS Gothic&quot;>Record " & iDelete & " was deleted.</font></td></tr>"
      End If
    Else

      'Print out the field names using some of the methods and properties
      ' of the Recordset object.
      Response.Write "<tr>"

      'For each column in the current row...
      For i = 1 to (objRS.Fields.Count - 1)
          ' write out the field name.
          Response.Write "<td><font face=&quot;MS Gothic&quot;><B>" & objRS(i).Name & "</B></font></td>"
      Next

      Response.Write "<td><font face=&quot;MS Gothic&quot;><B>Delete</B></font></td>"
      Response.Write "</tr>"

      'Print out the field data, using some other methods and properties
      ' of the Recordset object. When you see a pattern in how they are used,
      ' you can look up others and experiment.

      'While not at the end of the records in the set...
      While Not objRS.EOF

        Response.Write "<tr>"

        'For each column in the current row...
        For i = 1 to (objRS.Fields.Count - 1)
          ' write out the data in the field.
          Response.Write "<td><font face=&quot;MS Gothic&quot;>" & objRS(i) & "</font></td>"
        Next

        'Add a button that will pass in an ID number to delete a record.
        %><td><INPUT TYPE="SUBMIT" NAME="Delete" VALUE="<%=objRS(0)%>"></td><%

        Response.Write "</tr>"

        'Move to the next row.
        objRS.MoveNext

      Wend

    End If   'objRS.EOF
  %>
  </table>
  </FORM>

  <%
  'Close the Connection.
  objConn.Close
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

  View Guest Book

 
  Sort by which column:  
  Name Contains:
  E-mail Address Contains:
  CC Contains:
  Subject Contains:
  Memo Contains:
 

 
  There are no entries in the database.


단원 4: Excel 스프레드시트 표시

이 단원에서는 시스템에 설치된 Microsoft Excel이 필요하며 64비트 플랫폼용 Excel이 개발될 때까지는 64비트 플랫폼에서 지원되지 않습니다.

이 단원에서는 웹 페이지에서 Microsoft Excel 스프레드시트를 표시하는 방법에 대해 설명합니다. 이전 단원과 같이 ADO를 사용합니다. 그러나 이 단원에서는 Access 데이터베이스 대신 Excel 스프레드시트로 연결합니다.

Excel 스프레드시트를 준비하여 Active Server Page에 표시

  1. Excel 98이나 Excel 2000을 사용하여 스프레드시트를 만들어 x:\Inetpub\Wwwroot\Tutorial에 ASPTOC.xls로 저장합니다. 스프레드시트를 만들 때 특별한 서식이나 열 레이블을 포함시키지 마십시오.
  2. 몇몇 필드에 임의의 데이터를 입력합니다. 셀의 첫 번째 행을 열 이름으로 처리합니다.
  3. 스프레드시트에서 웹 페이지에 표시할 행과 열을 강조합니다. 필드의 블록을 강조하려면 필드 중 하나를 클릭하고 마우스를 비스듬히 끕니다.
  4. 삽입 메뉴에서 이름을 선택하고 정의를 클릭합니다. 여기서 셀 이름과 범위를 사용하여 모든 통합 문서를 정의합니다.
  5. 강조한 셀 범위가 아래쪽에 올바르게 표시되는지 확인합니다 . 통합 문서 이름 MYBOOK을 입력하고 추가를 클릭합니다. MYBOOK을 변경할 때 이름 정의 창 아래쪽에 있는 참조 대상에 올바른 셀 범위가 표시되는지 확인합니다. 새로운 셀 블록을 강조한 다음 MYBOOK을 선택하는 것만으로는 셀 범위가 업데이트되지 않습니다.
  6. 통합 문서 목록에 이름이 나타나면 확인을 클릭합니다. 스프레드시트를 저장합니다.
  7. Excel을 닫고, ASP 페이지가 파일을 액세스할 수 있도록 파일 잠금을 제거합니다.

단원 3의 예제에서는 연결 문자열에 특정 ADO DLL로 매핑하는 공급자 이름을 지정했습니다. 이 예제에서는 드라이버 이름을 사용하여 ASP가 해당 드라이버 이름에 대한 기본 공급자를 사용하게 합니다.

다음 코드를 복사하여 텍스트 편집기에 붙여넣고 x:\Inetpub\Wwwroot\Tutorial 디렉터리에 파일을 ViewExcel.asp로 저장합니다. 주소 표시줄에 http://localhost/Tutorial/ViewExcel.asp 를 입력하여 브라우저에서 예제를 봅니다.

  <%@ Language=VBScript %>

  <html>
  <head>
  <title>Display an Excel Spreadsheet in a Web Page</title>
  </head>
  <body>
  <font face="MS Gothic">
  <h2>Display an Excel Spreadsheet in a Web Page</h2>

  <%
   'Create your connection string, create an instance of the Connection object,
   ' and connect to the database.
   strDriver = "Driver={Microsoft Excel Driver (*.xls)};DBQ=C:\Inetpub\Wwwroot\Tutorial\MyExcel.xls;"
   Set objConn = Server.CreateObject("ADODB.Connection")
   objConn.Open strDriver

   'Selects the records from the Excel spreadsheet using the workbook name you saved.
   strSELECT = "SELECT * from `MYBOOK`"

   'Create an instance of the ADO Recordset object, and connect it to objConn.
   Set objRS = Server.CreateObject("ADODB.Recordset")
   objRS.Open strSELECT, objConn

   'Print the cells and rows in the table using the GetString method.
   Response.Write "<H4>Get Excel data in one string with the GetString method</H4>"
   Response.Write "<table border=1 ><tr><td>"
   Response.Write objRS.GetString (, , "</td><td><font face=&quot;MS Gothic&quot;>", "</font></td></tr><tr><td>", NBSPACE)
   Response.Write "</td></tr></table>"

   'Move to the first record.
   objRS.MoveFirst

   'Print the cells and rows in the table using the ViewGB.asp method.
   Response.Write "<H4>Get Excel data using MoveNext</H4>"

   'Print out the field names using some of the methods and properties
   ' of the Recordset object.
   Response.Write "<table border=1 ><tr>"

   'For each column in the current row...
   For i = 0 to (objRS.Fields.Count - 1)
     ' write out the field name.
     Response.Write "<td><font face=&quot;MS Gothic&quot;><B>" & objRS(i).Name & "</B></font></td>"
   Next

   'While not at the end of the records in the set...
   While Not objRS.EOF

     Response.Write "</tr><tr>"

     'For each column in the current row...
     For i = 0 to (objRS.Fields.Count - 1)
       ' write out the data in the field.
       %><td><font face="MS Gothic"><%=objRS(i)%></font></td><%
     Next

     'Move to the next row.
     objRS.MoveNext

   Wend

   Response.Write "</tr></table>"

   'Close the Connection.
   objConn.Close
  %>

  </font>
  </body>
  </html>

브라우저에 다음과 같이 표시되어야 합니다.

  Display an Excel Spreadsheet in a Web Page

  Get Excel data in one string with the GetString method

A2B2C2
A3B3C3

  Get Excel data using MoveNext

A1B1C1
A2B2C2
A3B3C3

다음: ASP 페이지에서 COM 구성 요소 사용


ⓒ 1997-2001 Microsoft Corporation. All rights reserved.