9º Unidad Didáctica ACTIVE SERVER PAGES (ASP) Eduard Lara 1 Objetos en ASP Existen 6 objetos en ASP. Qué es un objeto? Es una instancia de un componte. Well an object is an instance of a Component which has methods and properties. I am not going to indulge into what Components are except that they are a compiled piece of code built in any programming language which offer you the ability to just create an instance of them ( create an object ) and start using their methods. ASP is so much powerful that not only it uses these six built-in Objects but can also call other applications or components like ADO to access databases and CDO for messaging applications. You can even build your own custom COM components and then call their methods from within ASP. This is ASP COM integration which gives ASP is so much power that no other server side scripting language can match. Six Built-in ASP Objects Following are the six Objects which are available to you without needing to create an instance of them and that's why they are called built-in Objects : Application ASPError Request Response Server Session 2 • • • • • • Application ASPError Request Response Server Session 3 Objeto Response El objeto Response se utiliza para enviar información. Puede ser para mandar a imprimir texto o variables al explorador. Primero veamos la impresión de texto simple con el método Response.Write Si ven en otros ejemplos ven una sintaxis similar a esta: <%= "algo aqui" %> es lo mismo que escribir <% Response.Write "algo aquí"%>. O sea que el = reemplaza al Response.Write Otra característica del método Response es la siguiente: Response.Redirect redirecciona al usuario hacia otra URL. Su funcionamiento es muy fácil. Veámoslo: <% 'Esto enviaría al usuario al index.htm del sitio acme.com Response.Redirect "http://www.acme.com/index.asp" %> Hay mas métodos para aplicar al objeto Response, por ejemplo Response.Cookies 4 Objeto Response <% 'con el apostrofe se escriben comentarios que no serán captados por el servidor. 'ahora explicaré el código. Response.Write "Hola Usuario... bienvenido a nuestra Web <BR>" Response.Write "Como ven se incluyen los tags de HTML en medio del código ASP" 'ahora imprmiremos una variable numérica. dim numero numero = 12 'ya declaramos la variable y le dimos un valor. 'ahora la sacaremos por pantalla. Response.Write (numero & "<BR>") 'los paréntesis no son necesarios aquí, solo hacen mas comprensible el código. 'el signo & es necesario para ingresar el TAG de HTML. Ver que los tags siempre van entre "". 'la modificamos y la imprimimos nuevamente. numero = numero + 3 Response.Write numero %> Estas líneas imprimen en el navegador lo siguiente: Hola Usuario... bienvenido a nuestra Web Como ven se incluyen los tags de HTML en medio del código ASP 12 15 5 ASP Active Server Pages (ASP) es una tecnología del lado servidor de Microsoft para páginas web generadas dinámicamente, que ha sido comercializada como un anexo a Internet Information Server (IIS). La tecnología ASP está estrechamente relacionada con el modelo tecnológico de su fabricante. Enlaces de interés http://www.w3schools.com/asp/default.as p 6 ASP ASP ha pasado por cuatro iteraciones mayores, ASP 1.0 (distribuido con IIS 3.0), ASP 2.0 (distribuido con IIS 4.0), ASP 3.0 (distribuido con IIS 5.0) y ASP.NET (parte de la plataforma .NET de Microsoft). Las versiones pre-.NET se denominan actualmente (desde 2002) como ASP clásico. En el último ASP clásico, ASP 3.0, hay siete objetos integrados disponibles para el programador, Application, ASPError, Request, Response, Server, Session y ObjectContext. Cada objeto tiene un grupo de funcionalidades frecuentemente usadas y útiles para crear páginas web dinámicas. 7 8 9 <html> <body> <% response.write"¡Hola Mundo!" %> </body> </html> Escribir texto en el cliente <html> <body> <% response.write("<h2>¡Hola Mundo!<br> Esta sentencia usa etiquetas HTML para formatear el texto </h2>") %> </body> Formatear el texto </html> <html> <body> <% Dim nombre nombre="Juan Soldado" response.write("Mi nombre es: " & nombre) %> </body> </html> Como crear una variable 10 <html> <body> Como crear una tabla en memoria (Array) <% Dim amigos(5) amigos(0) = "Angel" amigos(1) = "Luis" amigos(2) = "Josito" amigos(3) = "Pepe" amigos(4) = "Ignacio" amigos(5) = "Enrique" For i = 0 to 5 response.write(amigos(i) & "<br>") Next %> </body> Mi primer bucle </html> <html> <body> <% Dim i for i = 1 to 6 response.write("<h" & i & ">Esta es la cabecera " & i & "</h" & i & ">") next %> </body> </html> 11 <html> <body> <% Dim h h = hour(now()) response.write("<p>" & now()) response.write(" (Hora de Madrid (España)) </p>") If h < 12 then response.write("¡Buenos Dias!") else response.write("¡Buenas tardes!") end if %> </body> </html> <html> <body> Hoy es dia: <%response.write(date())%>. <br> La hora local del servidor es: <%response.write(time())%>. </body> </html> ¿Qué hora es? Dia y Horas 12 Formularios (metodo GET) <html> <body> <form action="23basic.asp" method="get"> Pon tu nombre: <input type="text" name="fname"><br><br> <input type="submit" value="Submit"> </form> <% If Request.QueryString("fname")<>"" Then Response.Write ("Hola " & Request.QueryString("fname") & "!") Response.Write ("<br>¿Como estas hoy?") End If %> </body> </html> 13 Formularios (metodo POST) <html> <body> <form action="24basic.asp" method="post"> Pon tu nombre: <input type="text" name="fname"><br><br> <input type="submit" value="Submit"> </form> <% If Request.form("fname")<>"" Then Response.Write ("Hola " & Request.form("fname") & "!") Response.Write ("<br>¿Como estas hoy?") End If %> </body> </html> 14 Sistema de validación clásico This system works with five different pages: password.asp is the form users fill out. engine.asp is the VBScript that checks their entries. invalid.asp is the page users get from invalid login and password. inyougo.asp is the page they get with correct login and password. passwords.txt is the text page that contains the passwords. 15 Save this page as password.asp <%@ LANGUAGE="VBSCRIPT" %> <!--- This example is a simple login system ---> <HTML> <HEAD> <TITLE>Password.asp</TITLE> </HEAD> <BODY> <FORM ACTION="engine.asp" NAME="form1" METHOD="post"> User Name: <INPUT TYPE="text" SIZE=30 NAME="username"> <P> Password: <INPUT TYPE="password" SIZE=30 NAME="password"> <P> <INPUT TYPE="submit" VALUE="Login"> </FORM> </BODY> </HTML> 16 Save this page as engine.asp <%@ LANGUAGE="VBSCRIPT" %> <% ' Connects and opens the text file ' DATA FORMAT IN TEXT FILE= "username<SPACE>password" Set MyFileObject=Server.CreateObject("Scripting.FileSystemObject") Set MyTextFile=MyFileObject.OpenTextFile(Server.MapPath("\path\path\path\path") & "\passwords.txt") ' Scan the text file to determine if the user is legal WHILE NOT MyTextFile.AtEndOfStream ' If username and password found IF MyTextFile.ReadLine = Request.form("username") & " " & Request.form("password") THEN ' Close the text file MyTextFile.Close ' Go to login success page Session("GoBack")=Request.ServerVariables("SCRIPT_NAME") Response.Redirect "inyougo.asp" Response.end END IF WEND ' Close the text file MyTextFile.Close ' Go to error page if login unsuccessful Session("GoBack")=Request.ServerVariables("SCRIPT_NAME") Response.Redirect "invalid.asp" Response.end %> 17 Save this page as invalid.asp <%@ LANGUAGE="VBSCRIPT" %> <!--- This example is a simple login system ---> <HTML> <HEAD> <TITLE>invalid.asp</TITLE> </HEAD> <BODY> You have entered an invalid username or password. <P> <A HREF="password.asp">Try to log in again</A> </BODY> </HTML> 18 Save this page as inyougo.asp <%@ LANGUAGE="VBSCRIPT" %> <!--- This example is a simple login system ---> <HTML> <HEAD> <TITLE>In You Go</TITLE> </HEAD> <BODY> You have now entered the password protected page. </BODY> </HTML> 19 Save this page as passwords.txt gates bill burns joe 20