Download Java Servlets - Universidad Complutense de Madrid

Document related concepts
no text concepts found
Transcript
Java Servlets
Luis Fernando Llana Dı́az
Departamento de Sistemas Informáticos y Computación
Universidad Complutense de Madrid
22 de abril de 2008
Luis Fernando Llana Dı́az
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
¿Qué es un programa?
input
Programa
output
En pascal:
program holaMundo ( input , output );
var
nombre : String ;
begin
readLn ( nombre );
writeLn ( ’ Hola ’ , nombre );
end .
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Un servlet
input −→ HttpServletRequest.
output −→ HttpServletResponse (X)HTML, XML.
import javax . servlet .*;
import javax . servlet . http .*;
import java . io .*;
public class HolaMundo extends HttpServlet {
public final void doGet ( final H tt p Se r vl et R eq u es t request ,
final H t t p S er v l e t R e s p on s e response )
throws ServletException , IOException {
S e r v le t O u t p u t S tr e a m out = response . getOutputStr ea m ();
String nombre = request . getParamter ( " nombre " );
response . setContentType ( " text / html ; charset = UTF -8 " );
if ( nombre == null ) {
out . println ( " <p > Hola Mundo </ p > " );
} else {
out . println ( " <p > Hola " + nombre + " </p > " );
}
}
}
Luis Fernando Llana Dı́az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Servidor de aplicaciones: Tomcat
Los severlet son controlados por servidor de aplicaciones.
Tomcat: http://jakarta.apache.org/tomcat/index.html
Cuando una petición llega
1 Si el objeto de la clase no ha sido creado
Carga la clase
Crea el objeto
3 Invoca el método init.
1
2
2
Llama al método service.
Si debe eliminar al servlet llama al método destroy.
Luis Fernando Llana Dı́az
Java Servlets
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Interfaz javax.servlet.Servlet
void destroy()
void init(ServletConfig config)
void service(ServletRequest req, ServletResponse res)
Clase javax.servlet.http.HttpServlet
void doGet(HttpServletRequest req, HttpServletResponse resp)
void doPost(HttpServletRequest req, HttpServletResponse resp)
Luis Fernando Llana Dı́az
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Servlet contador I
public class Contador extends HttpServlet {
private int contador ;
/*
Metodos para guardar el contador antes de
f i n a l i z a r y leerlo al empezar . . . . . . . . . . . .
*/
private synchronized int incrementa () {
contador ++;
return contador ;
}
public final void doGet ( final H tt p Se r vl et R eq u es t request ,
final H t t p S er v l e t R e s p on s e response )
throws ServletException , IOException {
int n = incrementa ();
S e r v l et O u t p u t S t re a m out = response . getOutputS tr eam ();
response . setContentType ( " text / html ; charset = UTF -8 " );
out . println ( " <p > Numero de accesos : " + n + " </p > " );
}
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Servlet contador II
private ServletConfig config ;
private final static String strFichero = " fichero " ;
public final void init ( final ServletConfig c )
throws ServletException {
config = c ;
ServletContext ctx = config . ge tSe rvle tCo nte x t ();
String fichero = config . getInitParameter ( strFichero );
try {
BufferedReader f
= new BufferedReader (
new FileReader ( ctx . getRealPath ( fichero )));
contador = Integer . parseInt ( f . readLine ());
f . close ();
} catch ( F i l e N o t F o u n d E x c e p t i o n e ) {
contador = 0;
} catch ( IOException e ) {
contador = 0;
}
}
Luis Fernando Llana Dı́az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Servlet contador III
public final void destroy () {
ServletContext ctx = config . ge tSe rvle tCo nte x t ();
String fichero = config . getInitParameter ( strFichero );
try {
FileWriter f = new FileWriter ( ctx . getRealPath ( fichero ));
f . write ( contador + " \ n " );
f . close ();
} catch ( IOException e ) {
throw new RuntimeException ( e . g e t L o c a li z e d M e s s a ge ());
}
}
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Aplicación Hola I
TOMCAT_HOME / webapps / hola
| - - build . xml
| - - contador . txt
| - - html
|
| - - cabecera . html
|
‘-- pie . html
| - - prj . el
| - - src
|
| - - Contador . java
|
| - - Debug . java
|
| - - EnvoltorioHTML . java
|
| - - Fecha . java
|
| - - HolaMundo . java
|
| - - IncluyeFichero . java
|
| - - Login . java
|
‘-- Sesion . java
‘-- WEB - INF
| - - classes
|
| - - Contador . class
|
| - - Debug . class
|
| - - EnvoltorioHTML . class
|
| - - Fecha . class
|
| - - HolaMundo . class
|
| - - IncluyeFichero . class
|
| - - Login . class
|
‘-- Sesion . class
| - - lib
Luis Fernando Llana Dı́az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Aplicación Hola II
‘-- web . xml
28
Fichero web.xml
<? xml version = " 1.0 " encoding = " utf -8 " ? >
<web - app >
< display - name > Servlets de prueba </ display - name >
< servlet >
< servlet - name > hola </ servlet - name >
< servlet - class > HolaMundo </ servlet - class >
</ servlet >
< servlet >
< servlet - name > contador </ servlet - name >
< servlet - class > Contador </ servlet - class >
< init - param >
< param - name > fichero </ param - name >
< param - value > contador . txt </ param - value >
</ init - param >
</ servlet >
< servlet - mapping >
< servlet - name > invoker </ servlet - name >
<url - pattern >/ http /* </ url - pattern >
</ servlet - mapping >
< servlet - mapping >
< servlet - name > invoker </ servlet - name >
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Aplicación Hola III
<url - pattern >/ servlet /* </ url - pattern >
</ servlet - mapping >
</ web - app >
Luis Fernando Llana Dı́az
22
23
24
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Sesiones
Memoria entre diferentes invocaciones a servlets.
HttpSession sesion = request . getSession ();
String nombre =( String ) sesion . getAttribute ( strNombre );
Integer numAccesos = ( Integer ) sesion . getAttribute ( strNumAccesos );
if ( numAccesos == null ) {
numAccesos = new Integer (0);
}
sesion . setAttribute ( strNumAccesos , new Integer ( numAccesos . intValue ()+1));
. ..............
. ..............
if ( borroSesion != null ) {
contenido . append ( sesionBorrada ( response ));
sesion . removeAttribute ( strNumAccesos );
sesion . removeAttribute ( strNombre );
}
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Sesiones
Reescritura de URL
Cookies
Luis Fernando Llana Dı́az
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Sesiones
Toda URL debe ser codificada. Funciona tanto si tiene como si no
tiene las cookies habilitadas.
private StringBuffer
f or mu l ar i oC o n t in u a ( H t t p S e r vl e t R e s p o n s e response ) {
StringBuffer sb = new StringBuffer ();
sb . append ( " < form type =\" get \" action =\" " )
/* Se c odifica la URL , para que sea
i n d e p e n d i e n t e de las cookies */
sb . append ( response . encodeURL ( config . getServletName ()));
sb . append ( " \" >\ n " );
sb . append ( " <p > < button name =\" continuar \" type =\" submit \" > " );
sb . append ( " Continuar </ button > </p >\ n " );
sb . append ( " <p > < button name =\" " );
sb . append ( strBorraSesion );
sb . append ( " \" type =\" submit \" > Borrar sesion </ button > </p >\ n " );
sb . append ( " </ form >\ n " );
return sb ;
}
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Atributos
Se pueden guardar atributos
public
public
public
public
1
2
3
4
void setAttribute ( String name , Object o );
void removeAttribute ( String name );
Object getAttribute ( String name );
Enumeration g e tAtt rib ute Nam es ();
ServletRequest Atributos que sólo viven en una petición.
HttpSession Atributos que viven mientras dure la sesión.
ServletContext Atributos comunes para todos los servlets.
Luis Fernando Llana Dı́az
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Filtros
Transformar la salida del servlet
request
request
request
Filtro 1
response
request
Filtro 2
response
Filtro 3
Servlet
response
response
Aplicaciones:
autentificación,
cifrado,
transformaciones XML,
lo que se quiera....
Luis Fernando Llana Dı́az
Java Servlets
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
public class EnvoltorioHTML implements Filter {
private static final String cabecera = " html / cabecera . html " ;
private static final String pie = " html / pie . html " ;
private static final String strTitulo = " titulo " ;
private FilterConfig conf ;
public void init ( FilterConfig filterConfig )
throws ServletException {
conf = filterConfig ;
}
public void destroy () {
conf = null ;
}
public void doFilter ( ServletRequest request ,
ServletResponse response ,
FilterChain filterChain )
throws IOException , ServletException {
String fichero =
conf . g etS erv let Con text (). getRealPath ( cabecera );
String cabecera = IncluyeFichero . incluye ( fichero );
String titulo = conf . getInitParameter ( strTitulo );
S e r v l et O u t p u t S t re a m out = response . getOutputStre am ();
cabecera = cabecera . replaceAll ( " < title > " ,
" < title > " + titulo );
out . println ( cabecera );
filterChain . doFilter ( request , response );
fichero = conf . g etS ervl etC ont ext (). getRealPath ( pie );
out . println ( Incl uyeFichero . incluye ( fichero ));
}
Luis Fernando Llana Dı́az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
html/cabecera.html
<! DOCTYPE HTML PUBLIC " -// W3C // DTD HTML 4.01// EN " >
< html >
< head >
< meta http - equiv = " Content - Type " content = " text / html ; charset = utf -8 " >
< title > </ title >
</ head >
< body >
1
2
3
4
5
6
7
html/pie.html
< hr >
< address >
<a href = " mailto : lu is@ ram onv azq uez . net " >
Luis Fernando Llana Diaz
</ a >
</ address >
</ body >
</ html >
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
..... parametros globales de la aplicacion
< filter >
< filter - name > envoltorioHola </ filter - name >
< filter - class > En voltorioHTML </ filter - class >
< init - param >
< param - name > titulo </ param - name >
< param - value > Hola Mundo </ param - value >
</ init - param >
</ filter >
< filter >
< filter - name > en vo l to r io Co n ta d or </ filter - name >
< filter - class > En voltorioHTML </ filter - class >
< init - param >
< param - name > titulo </ param - name >
< param - value > Ejemplo de contador </ param - value >
</ init - param >
</ filter >
< filter - mapping >
< filter - name > envoltorioHola </ filter - name >
<url - pattern >/ http / hola </ url - pattern >
</ filter - mapping >
< filter - mapping >
< filter - name > en vo l to r io Co n ta d or </ filter - name >
<url - pattern >/ http / contador </ url - pattern >
</ filter - mapping >
definicion de servlets .....
Luis Fernando Llana Dı́az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
public class Login implements Filter {
.................................................
public final void doFilter ( final ServletRequest request ,
final ServletResponse response ,
final FilterChain filterChain )
throws IOException , ServletException {
HttpSession sesion =
(( H t tp Se r vl e tR eq u es t ) request ). getSession ();
String nombre =( String ) sesion . getAttribute ( Sesion . strNombre );
if ( nombre == null ) {
nombre = request . getParameter ( strNombre );
if ( nombre == null ) {
pideNombre (( Ht t pS er v le t Re qu e st ) request ,
( H t t p S er v l e t R e s p on s e ) response );
} else {
sesion . setAttribute ( Sesion . strNombre , nombre );
filterChain . doFilter ( request , response );
}
} else {
filterChain . doFilter ( request , response );
}
}
}
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
public class Login implements Filter {
private static final String strServlet = " servlet " ;
private static final String strNombre = " nombre " ;
private FilterConfig config ;
public void init ( FilterConfig filterConfig )
throws ServletException {
config = filterConfig ;
}
public void destroy () { }
private void pideNombre ( final H tt pS e rv l et Re q ue s t request ,
final H t t p S er v l e t R e s p on s e response )
throws IOException , ServletException {
S e r v l et O u t p u t S t re a m out = response . getOutputStre am ();
String uri = request . getRequestURI ();
response . setContentType ( " text / html ; charset = UTF -8 " );
out . println ( " < form type =\" get \" action =\" " + response . encodeURL ( uri )+ " \" >\ n " );
out . println ( " <p >\ n " );
out . println ( "
< label for =\" " + strNombre + " \" > Nombre : </ label > " );
out . println ( "
< input id =\" " + strNombre + " \" name =\" " + strNombre + " \" >\ n " );
out . println ( "
< button type =\" submit \" > Login </ button >\ n " );
out . println ( " </p >\ n " );
out . println ( " </ form > " );
}
public final void doFilter (...........)
}
Luis Fernando Llana Dı́az
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
Invocando otros servlets
public class Fecha extends HttpServlet {
public static final String strServlet = " / http / fecha " ;
public static final String strID = " id " ;
public final void doGet ( final H tt p Se r vl et R eq u es t request ,
final H t t p S er v l e t R e s p on s e response )
throws ServletException , IOException {
S e r v l et O u t p u t S t re a m out = response . getOutputStre am ();
response . setContentType ( " text / html ; charset = UTF -8 " );
Date hoy = new Date ();
DateFormat df = DateFormat . getDateInstance ( DateFormat . FULL );
out . println ( " < div id =\" " + request . getAttribute ( strID )+ " \" > " );
out . println ( df . format ( hoy ));
out . println ( " </ div > " );
}
}
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Incluir el resultado del servlet /http/fecha en cualquier parte
......
Re que stD ispa tch er rd =
request . g e t R e q u e s t D i s p a t c h e r ( Fecha . strServlet );
request . setAttribute ( Fecha . strID , " fecha " );
rd . include ( request , response );
......
Luis Fernando Llana Dı́az
1
2
3
4
5
6
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Servlets
El servlet /http/sesion I
..... otros filtros
< filter >
< filter - name > envoltorioSesion </ filter - name >
< filter - class > En voltorioHTML </ filter - class >
< init - param >
< param - name > titulo </ param - name >
< param - value > Ejemplo de uso de sesiones </ param - value >
</ init - param >
</ filter >
< filter >
< filter - name > loginSesion </ filter - name >
< filter - class > Login </ filter - class >
< init - param >
< param - name > servlet </ param - name >
< param - value > sesion </ param - value >
</ init - param >
</ filter >
... otros filtros
Luis Fernando Llana Dı́az
Java Servlets
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
El servlet /http/sesion II
< filter - mapping >
< filter - name > loginSesion </ filter - name >
<url - pattern >/ http / sesion </ url - pattern >
</ filter - mapping >
... otras disposiciones de filtros
1
2
3
4
5
6
7
8
9
10
11
12
..... otros servlets
< servlet >
< servlet - name > sesion </ servlet - name >
< servlet - class > Sesion </ servlet - class >
</ servlet >
< servlet >
< servlet - name > fecha </ servlet - name >
< servlet - class > Fecha </ servlet - class >
</ servlet >
... otros servlets
1
2
3
4
5
6
7
8
9
10
..... otras disposiciones de filtros
<! -- el orden es i m p o r t a n t e -- >
< filter - mapping >
< filter - name > envoltorioSesion </ filter - name >
<url - pattern >/ http / sesion </ url - pattern >
</ filter - mapping >
Luis Fernando Llana Dı́az
Java Servlets
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid