Tema3.a: ServidoresWeb

6
1 Tema 3.a: Servidores Web 2 Acceso a Páginas Web en ficheros Server host Client host GET /index.html Cabeceras + Content of index.html Open(f,“./indexhtml”); Read(f); Close(f); Output HTTP server: Apache, IIS Disco Duro Web Client: Iexplorer, FireFox SO Unix 3 Interfaces Web – Aplicaciones CGI: Common Gateway Interface Server host http://grid-nodo1.unavarra.es Client host GET /index.html Content of index.html GET /Hello.pl exec “./Hello.pl” Output of Program HTTP server: Apache, IIS CGI program Web Client: Iexplorer, FireFox Output of Program CGI Interface Sistema Operativo Unix 4 Interface Web- Aplicaciones: CGI (II) •CGI program in Perl, hello.pl •CGI program in C, hello.c -> hello.exe # Hello.pl print "Content-type: text/html\n\n"; print "<font color = blue>\n"; print "<h1>Hello, World</h1>\n"; print "</font>\n"; #include <stdio.h> main(int argc, char *argv[]) { printf("Content-type: text/html%c%c",10,10); printf("<font color = blue>"); printf("<H1>Hello there!</H1>"); printf("</font>"); } Content-type: text/html\n\n <font color = blue> <H1>Hello there!</H1> </font> HTML

Transcript of Tema3.a: ServidoresWeb

1

Tema3.a:

ServidoresWeb

2

Accesoa PáginasWeb en ficheros

Server host

Clienthost

GET /index.html

Cabeceras +

Contentofindex.html

Open(f,“./indexhtml”);

Read(f);

Close(f);

OutputHTTP server:

Apache, IIS

Disco Duro

Web Client:

Iexplorer,

FireFox

SO Unix

3

Interfaces W

eb –Aplicaciones

CGI: Com

mon Gateway Interface

Server host

http://grid-nodo1.unavarra.es

Clienthost

GET /index.html

Contentofindex.html

GET /Hello.pl

exec“./Hello.pl”

Output ofProgram

HTTP server:

Apache, IIS

CGI program

Web Client:

Iexplorer,

FireFox

Output ofProgram

CGI Interface

Sistema Operativo Unix

4

Interface Web-Aplicaciones:

CGI (II)

•CGI program in Perl, hello.pl

•CGI program in C, hello.c-> hello.exe

# Hello.pl

print"Content-type: text/html\n\n";

print"<fontcolor = blue>\n";

print"<h1>Hello, World</h1>\n";

print"</font>\n";

#include<stdio.h>

main(intargc, char*argv[]) {

printf("Content-type: text/html%c%c",10,10);

printf("<fontcolor = blue>");

printf("<H1>Hellothere!</H1>");

printf("</font>");

}

Content-type: text/html\n\n

<fontcolor = blue>

<H1>Hellothere!</H1>

</font>

HTML

5

Interface Web-Aplicaciones:

CGI (III)

El interface CGIespecificacomoel procesoservidorWeb comunicaal proceso

externoinformaciónsobrela peticióndel clienteescribiendolaen variables de

entorno, pe.:

REQUEST_METHOD: contieneinformaciónsobreel metodode la petición,

QUERY_STRING: contieneun string con losdatosdel formulariorellenadoporel

cliente,

CONTENT_TYPE: contieneel tipode datosde la petición,

main(intargc, char*argv[]) {

char*cl;

printf("Content-type: text/html%c%c",10,10);

if(strcmp(getenv("REQUEST_METHOD"),

"GET"))

{

printf("Thisscriptshouldbe referenced

witha METHOD ofGET.%c", 13);

exit(1);

} cl= getenv("QUERY_STRING");

if(cl== NULL) {

printf("No querytodecode.%c",13);

exit(1);

}

GET

Hello.cgi&

Name=Pepe

%setREQUEST_METHOD=GET

%setQUERY_STRING=“Name=Pepe”

% exec“./Hello.pl”

Sistema Operativo Unix

Client

Web

Server

6

Interface Web–Aplicacion:

CGI (IV)

Web Server

exec“./Hello.pl”

exec“./Hello.pl”

exec“./Hello.pl”

Pid=12

Pid=13

Pid=14

Sistema Operativo

Cliente 1

Cliente 2

Cliente 3

1 Petición->

1 Procesodel SO.

(apartede los

procesosque

puedacrearel

servidorweb)

7

Interface Web-Aplicación:

CGI (V)

�Ventajas:

�Interface simple,

�No hay quemodificarprogramas.

�Desventajas:

�Alto tiemporespuesta: creaciónde procesoses

costosa.

�Pocaescalabilidad: 1 procesoporclienteconsumen

muchosrecursos.

�Problemasde seguridad: accesoa shell.

8

Interface

Web-Aplicaciones:

API de Servidor

(I)

Web Server

Sistema

Operativo

Cliente 1

Cliente 2

Cliente 3

•AplicaciónconstruidasobreAPI

del servidorWeb: Apache API,

IIS API, etc.

•Aplicacióncompiladacon

servidorWeb comolibreria

dinámica.so o .dll.

•Códigode aplicacióncargado

con procesoservidor.

•No se creaotroprocesopor

petición.

•Bugs en aplicaciónhacenfallar

al procesoservidor.

Hello(null);

9

Interface

Web-Aplicaciones:

API de Servidor

(II)

Web Server

Sistema

Operativo

Cliente 1

Cliente 2

Cliente 3

Mod_php(Func);

•Peroalgunaslibrerías

implementadascon APIs son

muyestablesy muyusadas.

•mod_perl, mod_phpen

Apache permiteejecutarscripts

en procesoservidorcon buen

rendimiento.

•Cadapeticiónde script perlo

phpse ejecutaen el mismo

procesodel servidorque

atiendela petición(muybuen

tiempode respuesta).

Read.php

View.php

Write.php

Cada proceso:

1)Atiende petición

2) procesa script

10

Arquitectura Apache

Apache v1 esun servidormultiproceso:

Cadapeticionesatendidaporun proceso.

Pre-forking:

Inicializaciónservidor:

*ArrancarN procesos(pool).

*N configurable en httpd.conf.

Llegapeticióna “accept Socket”:

*Pedira procesono utilizadoque

cree“data socket”y procesela

petición. (buentiemporespuesta).

Dependiendode la cargadel servidor, el proceso

principal arrancamásservidoreso losmata.

Apache v2 esmultihilo(en C y multiplataforma).

Web

Client

Apache

Web Server

Fork()

Fork()

Accept

socket

Fork()

Fork()

Data

socket

11

Apa

che vs. servidor

Java

�Aplicación cargada

en JVM de servidor.

�Aplicaciones

multihilo.

�Lectura ficheros

no eficiente

�Protocolo HTTPS

no eficiente.

Servidor

JAVA

�Acceso a ficheros

eficiente.

�protocolo seguro

HTTPS

�Acceso a

aplicaciones no

eficiente (CGI) o

no robusto (API)

Apache

Ventajas

Incovenientes

12

Servlet(I)

Server host

http://grid-nodo1.unavarra.es

Clienthost

GET /index.html

Contentofindex.html

GET /MSPservlet

MSPservlet.doGet()

Output ofServlet

HTTP server:

Tomcat

Servlet

Web Client:

Iexplorer,

FireFox

Output ofServlet

ServletInterface

Java Virtual Machine

13

Web Server+

Contenedor

Hello.doGet()

Sistema Operativo

Cliente1

Hilo1

Java Virtual Machine

Hello.doGet()

Hello.doGet()

Process

Servlet(II)

Hello

Hilo1

Hilo2

Hilo3

Cliente2

Cliente3

•Servletesun programa

queatiendepeticionesde

clientesWeb.

•Los servletsse ejecutan

en servidoresmultihilo

quereconocenel API

llamadoscontenedores:

(TOMCAT, JBOSS,.…)

•Porcadapeticiónde

clienteel contenedor

iniciaun hiloen el quese

ejecutael códigodel

Servlet.

14

Contenedorinit()

Sistema Operativo

Admin

Client

1.Administradordespliegua

Servlet: Save As../FTP/HTTP.

2.Administradorpidea

ContenedoriniciaServlet.

Hello.init();

3.PeticiónCliente.

4.Contenedor:

1.Creahilo, asignaa servlet.

2.llama a métodoServlet.

Hello.doGet();

3.Finaliza/reutilizahilo.

5.Vuelvea paso3.

6.Administradorpidea

ContenedorfinalizaServlet.

Hello.destroy();

Hilo1

Java Virtual Machine

Hello.doGet()

destroy()

Process

Ciclo de Vida de un Servlet

Hello

Hilo2

NO crea hilos.

15

Interface Servlet

(I)

HttpServletextiendela claseGenericServlet(tambiénexiste el interface Servlet).

Metodosde HttpServletquese sobreescribenparaprogramarel servicio:

voiddoGet(HttpServletRequestreq, HttpServletResponseresp)

voiddoPost(HttpServletRequestreq, HttpServletResponseresp)

voiddoPost(HttpServletRequestreq, HttpServletResponseresp)

voiddoDelete(HttpServletRequestreq, HttpServletResponseresp)

importjava.io.*;

importjavax.servlet.*;

importjavax.servlet.http.*;

publicclassHelloWorldextendsHttpServlet{

publicvoiddoGet(HttpServletRequestrequest, HttpServletResponseresponse)

throwsIOException, ServletException

{

response.setContentType("text/html");

PrintWriterout = response.getWriter();

out.println("<html>");

out.println("<head>");

out.println("<title>HelloWorld!</title>");

out.println("</head>");

out.println("<body>");

out.println("<h1>HelloWorld!</h1>");

out.println("</body>");

out.println("</html>");

}

}

Objeto tipo respuesta,

se rellenaran sus

campos.

Objeto tipo peticion,

contiene campos de

petición.

Escribe

Cabecera

Escribe

Cuerpo

16

Interface Servlet

(II)

Métodos de HttpServletRequest(no es necesario sobreescribir):

StringgetParameter(Stringname);

StringgetRemoteAddr()

StringgetHeader(Stringname)

IntgetContentLength()

BooleanisSecure()

StringgetRemoteUser()

HttpSessiongetSession()

Interface HttpServletResponse:

setContentType(Stringname)

setContentLength(intlen)

setHeader(Stringname, Stringname)

sendRedirect(jStringlocation)

addHeader(Stringname,Stringvalue)

importjava.io.*;

importjavax.servlet.*;

importjavax.servlet.http.*;

publicclassSubastaBMWextendsHttpServlet{

intpujaActual= 0;

publicvoiddoPost(HttpServletRequestrequest,

HttpServletResponseresponse)

throwsIOException, ServletException

{

pujaActual= Integer.parseInt

(request.getParameter("miPuja"));

response.setContentType("text/html");

PrintWriterout = response.getWriter();

out.println("<html><head><title>Gracias!</title>

</head><body>");

out.println(“Has pujado”+pujaActual);

out.println("</body></html>");

}

}

17

Interface Servlet

(III)

Servletspueden atender peticiones Web, u otros protocolos.

Metodosde Servlets(implementado por clase GenericServlet):

voidinit(ServletConfigconfig)

arranca el servlet, no se crea un hilo.

voidservice(ServletRequestreq, ServletResponseres)

llamado por el contenedor para atender una petición, crea un hilo y llama al

método correspondiente doGet, doPost, …

(no se sobreescribe)

ServletConfiggetServletConfig()

Devuelve un objeto de tipo ServletConfig, que contiene parámetros de i

nicializacióndel servlet.

StringgetServletInfo()

Devuelve información sobre el servlet: autor, version, etc.

voiddestroy()

El contenedor llama a este método para indicar al servletque ya no

atenderámás peticiones.

Se sobreescribepara finalizar conexiones actuales de manera ordenada.

18

TOMCAT (I)

•Contenedorde servlets: servidor

multihiloqueimplementael API

de Servlets(inicializalosservlets

llamandoal metodoinit(), por

cadapeticiónde clienteel

contenedoriniciaun hiloy llama

al metodoservice() del servlet,...)

•Tomcat 5.0 implementa

especificacionesServletsv2.4 y

JSP 2.0.

•Compuestode varios

componentesquepermiten

multiples configuraciones.

Contenedorinit()

Sistema Operativo

Cliente

Admin

Hilo1

Java Virtual Machine

NewHello()

service()

Process

Hello

Hilo2

destroy()

GET

init,

destroy

19

Com

ponentes TOMCAT (I)

Server:

•solo un server en unaJVM.

•VariasJVM (variosserver en una

máquina).

•1 Server -> N Servicios.

Servicio:

•Agrupa1 Engine y N Connectors.

•Engine recibepeticionesa travésde uno

o variosconectores.

Conector:

•Componentequerecibe

peticionesporun puertoen un

protocolo.

•Variostiposde conectores:

HTTP, HTTPS, AJP.

Engine:

•aceptapeticiones, lasreenviaa la

aplicacioncorrespondientesegúnlas

cabecerasy devuelverepuestas.

•1 Engine -> N Virtual Hosts.

20

Com

ponentes TOMCAT (II)

Hosts:

•Analogoa host virtualesde Apache.

•1 Host -> N Contextos.

Contexto:

•Equivalea unaaplicación.

•Identificarúnico.

•Contienevariosservlets, ficheros

HTML, y paginasJSP.

Valves:

•Interceptanlaspeticionesy lasprocesan,

•Utilizadosparaguardaren un ficheroun

log de peticiones, direccionesIP, etc.

Loggers:

•Guardanen un ficheroel log de los

errores, excepciones, etc quese producen

en un Engine, host o contexto.

21

Pool ThreadsTOMCAT

Pool de threads:

•Similar al pool de procesosde apache.

•Reutilizarthreads entrepeticiones.

Configuraciónen server.xml

•<Connector port="8080" maxThreads="150"

minSpareThreads="25" maxSpareThreads="75“…>

maxThreads:máximo numero de threadsque creara este conector,

es decir máximo numero de peticiones simultaneas que se

atenderán.

minSpareThreads: mínimo número de threadsque se crearan

cuando se cree el conector, y que se mantendrán mientras el

conector este disponible.

maxSpareThreads:máximo numero de threadsque se permite

estén libres, cuando se alcance este numero se comenzaran destruir

threads.

22

Administración TOMCAT

23

Aplicaciones en TOMCAT

1 Contexto-> 1 Aplicacion./webapps/”context-name”/

Estructuradirectorioes:

*.htm

l, *.jsp, etc.->

ficheros no compilados

/WEB-INF/web.xml----------->

descriptor de despliegue

(mapping, conf. sesiones, etc)

/WEB-INF/classes/->

clases de servlets

/WEB-INF/lib/->

libreriasde clases JAR

Archivosde tipoWAR:

*contienentodoslosficherosde unaaplicación.

*se instalanen directorio./webapps/ y TOMCAT losdescomprime.

<web-app>

<display-name>myServletWAR</display-name>

<description>Thisisa simple app</description>

<servlet>

<servlet-name>myHello</servlet-name>

<servlet-class>HelloServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>myHello</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

</web-app>

24