프로그래밍/ASP

ASP 객체 모델: Request, Response, Server, Application, Session 객체

shimdh 2025. 2. 6. 11:22
728x90

ASP(Active Server Pages)에서 제공하는 객체 모델은 클라이언트와 서버 간의 데이터 처리 및 상호작용을 효율적으로 관리할 수 있게 도와줍니다. 이번 포스트에서는 Request, Response, Server, Application, Session 객체의 주요 기능과 활용 방법을 하나의 흐름으로 정리하고, 실용적인 예제를 함께 살펴보겠습니다.


Request 객체: 클라이언트 요청 처리

Request 객체는 클라이언트가 서버에 보낸 요청 데이터를 처리하는 데 사용됩니다. 주로 사용자의 입력값을 읽고 이를 기반으로 동적인 콘텐츠를 생성합니다. 이 객체는 특히 폼 데이터, 쿼리 문자열, 쿠키 등 다양한 소스에서 데이터를 수집하는 데 유용합니다.

주요 속성과 예제

  • Request.QueryString: URL 쿼리 문자열에서 데이터를 가져옵니다. 주로 GET 방식의 요청에서 사용됩니다.

    Dim userName
    userName = Request.QueryString("name") ' URL: ?name=John -> 결과: "John"
  • Request.Form: HTML 폼에서 POST 방식으로 전송된 데이터를 읽습니다.

    Dim email
    email = Request.Form("email") ' 폼에서 입력된 이메일 값
  • Request.Cookies: 클라이언트의 쿠키 데이터를 가져옵니다.

    Dim userCookie
    userCookie = Request.Cookies("username") ' 쿠키 값 읽기
  • Request.ServerVariables: 서버와 클라이언트 간의 다양한 정보를 제공합니다.

    Dim clientIP
    clientIP = Request.ServerVariables("REMOTE_ADDR")
    Response.Write("클라이언트 IP: " & clientIP)
  • 로그인 처리 예제

    <form method="post" action="login.asp">
        ID: <input type="text" name="userID">
        Password: <input type="password" name="password">
        <input type="submit" value="Login">
    </form>
    
    <!-- login.asp -->
    <%
    Dim userID, password
    userID = Request.Form("userID")
    password = Request.Form("password")
    
    If userID = "admin" And password = "1234" Then
        Response.Write("<h1>환영합니다, 관리자님!</h1>")
    Else
        Response.Write("<h1>아이디 또는 비밀번호가 잘못되었습니다.</h1>")
    End If
    %>

Response 객체: 서버 응답 관리

Response 객체는 서버가 클라이언트에게 데이터를 전송하는 데 사용됩니다. HTML 콘텐츠 생성, HTTP 헤더 설정, 리다이렉션 등 다양한 작업을 수행할 수 있습니다.

주요 기능과 예제

  • HTML 콘텐츠 출력

    Response.Write("<h1>안녕하세요, 사용자님!</h1>")
  • HTTP 헤더 설정

    Response.ContentType = "text/html"
    Response.AddHeader("Cache-Control", "no-cache")
  • 페이지 리다이렉션

    Response.Redirect("http://example.com")
  • 쿠키 설정

    Response.Cookies("username") = "홍길동"
    Response.Cookies("username").Expires = DateAdd("d", 7, Now)
  • 폼 데이터 출력 예제

    <%
    If Request.Form("submit") <> "" Then
        Dim userName
        userName = Request.Form("username")
        Response.Write("<p>환영합니다, " & userName & "님!</p>")
    End If
    %>
    
    <form method="post">
        이름: <input type="text" name="username">
        <input type="submit" name="submit" value="제출">
    </form>

Server 객체: 서버 측 작업 관리

Server 객체는 서버 관련 작업을 지원하며, 동적 페이지 생성과 데이터 처리에 유용합니다.

주요 기능과 예제

  • URL 인코딩 및 디코딩

    Dim encodedString
    encodedString = Server.URLEncode("Hello World!")
    Response.Write("인코딩된 문자열: " & encodedString)
  • 파일 시스템 접근

    Dim filePath
    filePath = Server.MapPath("/uploads/")
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set folder = fso.GetFolder(filePath)
    
    For Each file In folder.Files
        Response.Write("파일 이름: " & file.Name & "<br>")
    Next
    
    Set folder = Nothing
    Set fso = Nothing
  • 페이지 경로 정보 확인

    Response.Write("현재 페이지 경로: " & Server.MapPath(Request.ServerVariables("SCRIPT_NAME")))

Application 객체: 애플리케이션 상태 관리

Application 객체는 애플리케이션 전역에서 데이터를 공유하는 데 사용됩니다.

주요 기능과 예제

  • 방문자 수 카운터

    If IsEmpty(Application("VisitorCount")) Then
        Application("VisitorCount") = 0
    End If
    
    Application.Lock()
    Application("VisitorCount") = Application("VisitorCount") + 1
    Application.Unlock()
    
    Response.Write("현재 방문자 수: " & Application("VisitorCount"))

Session 객체: 사용자 세션 관리

Session 객체는 개별 사용자의 상태 정보를 저장하고 유지합니다.

주요 기능과 예제

  • 세션 데이터 저장 및 읽기

    Session("UserName") = "홍길동"
    Response.Write("안녕하세요, " & Session("UserName") & "님!")
  • 세션 종료

    Session.Abandon()
  • 쇼핑 카트 구현

    Sub AddToCart(productId, quantity)
        If IsEmpty(Session("Cart")) Then
            Set cart = Server.CreateObject("Scripting.Dictionary")
            Set Session("Cart") = cart
        Else
            Set cart = Session("Cart")
        End If
    
        If cart.Exists(productId) Then
            cart(productId) = cart(productId) + quantity
        Else
            cart.Add productId, quantity
        End If
    End Sub
    
    AddToCart(101, 2)
    Response.Write("장바구니: " & Session("Cart")(101))

결론

ASP 객체 모델은 클라이언트-서버 간 데이터 처리와 동적 콘텐츠 생성을 효율적으로 지원합니다. 각 객체의 기능을 적절히 이해하고 활용하면 강력한 웹 애플리케이션을 개발할 수 있습니다.

핵심 요약:

  • Request: 클라이언트 데이터를 읽고 처리.
  • Response: 데이터를 클라이언트로 전송.
  • Server: 서버 리소스 관리.
  • Application: 전역 데이터 관리.
  • Session: 사용자별 데이터 관리.

이 객체들을 적절히 활용하여 더욱 효율적이고 유연한 웹 서비스를 구축하세요!

728x90