Download versión para imprimir - 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 10 de mayo de 2007 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 import javax . servlet .*; import javax . servlet . http .*; import java . io .*; public class HolaMundo extends HttpServlet { public final void doGet ( final H t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p o n s e response ) throws ServletException , IOException { S e r v l e t O u t p u t S t r e a m out = response . getOutputStre a m (); String nombre = request . getParamter ( " nombre " ); response . setContentType ( " text / html " ); 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 t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p o n s e response ) throws ServletException , IOException { int n = incrementa (); S e r v l e t O u t p u t S t r e a m out = response . getOutput St re a m (); response . setContentType ( " text / html " ); 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 Se rvle tExc epti on { config = c ; ServletContext ctx = config . g et Se r vl et C on t ex t (); String fichero = config . ge tIni tPar amet er ( 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 . g et Se r vl et C on t ex t (); String fichero = config . ge tIni tPar amet er ( strFichero ); try { FileWriter f = new FileWriter ( ctx . getRealPath ( fichero )); f . write ( contador + " \ n " ); f . close (); } catch ( IOException e ) { throw new Ru ntim eExc epti on ( e . g e t L o c a l i z e d M e s s a g e ()); } } 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 o r m u l ar i o C o n t i n u a ( H t t p S e r v l e t R e s p o n s e response ) { StringBuffer sb = new StringBuffer (); sb . append ( " < form type =\" get \" action =\" " ) /* Se codifica 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 removeAttribu te ( String name ); Object getAttribute ( String name ); Enumeration g et At t ri bu t eN a me s (); 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 Filtro 1 Filtro 2 Servlet 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 Se rvle tExc epti on { conf = filterConfig ; } public void destroy () { conf = null ; } public void doFilter ( ServletRequest request , Se rvletResponse response , FilterChain filterChain ) throws IOException , Se rvle tExc epti on { String fichero = conf . g et Se r vl e t C on t ex t (). getRealPath ( cabecera ); String cabecera = IncluyeFichero . incluye ( fichero ); String titulo = conf . ge tIni tPar amet er ( strTitulo ); S e r v l e t O u t p u t S t r e a m out = response . getOutputStrea m (); cabecera = cabecera . replaceAll ( " < title > " , " < title > " + titulo ); out . println ( cabecera ); filterChain . doFilter ( request , response ); fichero = conf . g et Se r vl et C on t ex t (). getRealPath ( pie ); out . println ( IncluyeFichero . 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 = iso -8859 -15 " > < title > </ title > </ head > < body > 1 2 3 4 5 6 7 html/pie.html < hr > < address > <a href = " mailto : lu i s@ ra m on va z qu ez . 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 > EnvoltorioHTML </ filter - class > < init - param > < param - name > titulo </ param - name > < param - value > Hola Mundo </ param - value > </ init - param > </ filter > < filter > < filter - name > e n v o l t or i o C o n t a d o r </ filter - name > < filter - class > EnvoltorioHTML </ 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 > e n v o l t or i o C o n t a d o r </ 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 , Se rvle tExc epti on { HttpSession sesion = (( H t t p S e rv l e t R e q u e s t ) request ). getSession (); String nombre =( String ) sesion . getAttribute ( Sesion . strNombre ); if ( nombre == null ) { nombre = request . getParameter ( strNombre ); if ( nombre == null ) { pideNombre (( H t t p S e rv l e t R e q u e s t ) request , ( H t t p S e r v l e t R e s p o n 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 Se rvle tExc epti on { config = filterConfig ; } public void destroy () { } private void pideNombre ( final H t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p o n s e response ) throws IOException , Se rvle tExc epti on { S e r v l e t O u t p u t S t r e a m out = response . getOutputStrea m (); String uri = request . getRequestURI (); response . setContentType ( " text / html " ); 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 t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p o n s e response ) throws ServletException , IOException { S e r v l e t O u t p u t S t r e a m out = response . getOutputStrea m (); response . setContentType ( " text / html " ); 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 ...... R e q ue s tD i s p at c he r 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 > en volt or io Sesi on </ filter - name > < filter - class > EnvoltorioHTML </ 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 > en volt or io Sesi on </ filter - name > <url - pattern >/ http / sesion </ url - pattern > </ filter - mapping > Luis Fernando Llana Dı́az Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Java Servlets Fichero hola.xml 1 2 3 4 < Resource name = " jdbc / DB - valores " auth = " Container " 5 type = " javax . sql . DataSource " 6 removeAbandoned = " true " r e m o v e A b a n d o n e d T i m e o u t = " 60 " logAbandoned = " true " 7 maxActive = " 100 " maxIdle = " 30 " maxWait = " 10000 " 8 username = " luis " password = " patata " 9 driverClassName = " com . mysql . jdbc . Driver " 10 url = " jdbc:mysql: // localhost:3306 / valores ? autoReconnect = true " / > 11 </ Context > 12 < Context docBase = " ${ catalina . home }/ server / webapps / hola " > < Logger className = " org . apache . catalina . logger . Syst em O u tL og g e r " / > < Logger className = " org . apache . catalina . logger . Syst em E r rL og g e r " / > Luis Fernando Llana Dı́az Java Servlets Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Conexion con la base de datos import import import import import java . sql . Connection ; java . sql . SQLException ; javax . naming . InitialContext ; javax . naming . NamingException ; org . apache . commons . dbcp . BasicDataSource ; public class Conexion { public static Connection g e t C o n ex i o n V a l o r e s () throws SQLException , NamingException { InitialContext ctx = new InitialContext (); BasicDataSource ds = ( BasicDataSource ) ctx . lookup ( " java : comp / env / jdbc / DB - valores " ); return ds . getConnection (); } } Luis Fernando Llana Dı́az 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 Java Servlets Listado de valores import soporte . html . Tags ; // Clase para f a c i l i t a r el uso de HTML / XML 1 public class Valores extends HttpServlet { 2 public final void doGet ( H t t p S e rv l e t R e q u e s t request , 3 H t t p S e r v l e t R e s p o n s e response ) 4 throws ServletException , IOException { 5 S e r v l e t O u t p u t S t r e a m out = response . getOutput S trea m (); 6 String nombre = request . getParameter ( " nombre " ); 7 response . setContentType ( " text / html " ); 8 try { 9 Connection con = Conexion . g e t C o n ex i o n V a l o r e s (); 10 P re pa r ed St a te m en t psmt = con . pr epar eSta te m e n t ( " select * from valores " ); 11 StringBuffer lista = new StringBuffer (); 12 ResultSet rs = psmt . executeQuery (); 13 while ( rs . next ()) { 14 lista . append ( Tags . li ( " " , Tags . a ( rs . getString ( " url " ) , " " , rs . getString (15 " nombre " )))); } 16 out . print ( Tags . h (1 , " " ," Lista de valores " )); 17 out . print ( Tags . ul ( " " , lista . toString ())); 18 con . close (); 19 } catch ( SQLException e ) { 20 throw new Se rvle tExc epti on ( e . getMessage () , e ); 21 } catch ( NamingException e ) { 22 throw new Se rvle tExc epti on ( e . getMessage () , e ); 23 } 24 } 25 } 26 Luis Fernando Llana Dı́az Java Servlets Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets I 1 2 3 4 public final void doGet ( final H t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p 5o n s e response ) throws ServletException , IOException { 6 response . setContentType ( " text / html " ); 7 HttpSession sesion = request . getSession (); 8 String accion = request . getParameter ( strAccion ); 9 if ( accion == null || accion . equals ( strPensar ) ) { 10 pensar ( request , response ); 11 } else { 12 comer ( request , response ); 13 } 14 } 15 public final void doGet ( final H t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p 16 o n s e response ) throws ServletException , IOException { 17 ............................. 18 } 19 public final void pensar ( final H t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s 20 p o n s e response ) throws ServletException , IOException { 21 ............................. 22 } 23 24 public class Filosofo extends HttpServlet { ............................. private static final String strAccion = " accion " ; } Luis Fernando Llana Dı́az Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Java Servlets Los filósofos con servlets II 1 2 public final void comer ( final H t t p S e rv l e t R e q u e s t request , final H t t p S e r v l e t R e s p 3o n s e response ) throws ServletException , IOException { 4 S e r v l e t O u t p u t S t r e a m out = response . getOutput S trea m (); 5 HttpSession sesion = request . getSession (); 6 Integer ID = ( Integer ) sesion . getAttribute ( strFilosofoID ); 7 try { 8 mesa . permisoComer ( ID . intValue ()); 9 out . println ( Tags . p ( " " ," Filósofo " + ID + " comiendo , cuando quiera pensar pulsar 10 el botón " )); out . println ( Tags . p ( " " ," Estado del monitor : " + mesa )); 11 12 String URI = (( H t t p S e rv l e t R e q u e s t ) request ). getRequestURI (); 13 out . println ( Tags . p ( " " , Tags . form ( response . encodeURL ( URI ) , " get " ," " , 14 Tags . button ( strAccion , Tags . strSubmit , strPensar 15 , " " ," Pensar " )))); } catch ( I n t e r r u p t e d E x c e p t i o n e ) { 16 throw new Se rvle tExc epti on ( e . getMessage () , e ); 17 } 18 } 19 public static final String strFilosofoID = " filosofoID " ; Luis Fernando Llana Dı́az Java Servlets Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets III private static final int NUM_FILOSOFOS =5; public static final String strMesa = " mesa " ; private Mesa mesa ; public final void init ( ServletConfig config ) throws Se r vl e t E x c e p t i o n { ServletContext ctx = config . g et Se r vl et C on t ex t (); Mesa ctxMesa = ( Mesa ) ctx . getAttribute ( strMesa ); if ( ctxMesa != null ) { mesa = ctxMesa ; } else { mesa = Mesa . getMesa ( NUM_FILOSOFOS ); ctx . setAttribute ( strMesa , mesa ); } } Luis Fernando Llana Dı́az 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 Java Servlets Los filósofos con servlets IV 1 2 3 4 private Mesa ( int n ) { 5 numFilosofos = n ;; 6 comiendo = new boolean [ numFilosofos ]; 7 for ( int i = 0; i < numFilosofos ; i ++) { 8 comiendo [ i ] = false ; 9 } 10 } 11 public static Mesa getMesa ( int n ) { 12 if ( mesa == null ) { 13 mesa = new Mesa ( n ); 14 } else { 15 if ( mesa . numFilosofos != n ) { 16 throw new Ru ntim eExc epti on ( " Monitor de filósofos ya construido con 17 " + mesa . numFilosofos + " filósofos . No puedo darte uno de " + n ); } 18 } 19 return mesa ; 20 } 21 ........................... 22 23 public class Mesa { ......................... private static Mesa mesa = null ; } Luis Fernando Llana Dı́az Java Servlets Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets V public class Login implements Filter { 1 ...................... 2 public final void doFilter ( final ServletRequest request , 3 final ServletResponse response , 4 final FilterChain filterChain ) 5 throws IOException , Se rvle tExc epti on { 6 HttpSession sesion = (( H t t p S e rv l e t R e q u e s t ) request ). getSession (); 7 Integer filosofoID =( Integer ) sesion . getAttribute ( Filosofo . strFilosofoID ); 8 if ( filosofoID == null ) { 9 String ID_str = request . getParameter ( Filosofo . strFilosofoID ); 10 if ( ID_str == null ) { 11 pideNombre (( H t t p S e rv l e t R e q u e s t ) request ,( H t t p S e r v l e t R e s p o n s e ) response 12); } else { 13 try { 14 Integer ID = new Integer ( ID_str ); 15 sesion . setAttribute ( Filosofo . strFilosofoID , ID ); 16 filterChain . doFilter ( request , response ); 17 } catch ( N u m b e r F o r m a t E x c e p t i o n e ) { 18 pideNombre (( H t t p S e rv l e t R e q u e s t ) request ,( H t t p S e r v l e t R e s p o n s e ) response 19 ); } 20 } 21 } else { 22 filterChain . doFilter ( request , response ); 23 } 24 } 25 Luis Fernando Llana Dı́az Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Java Servlets Los filósofos con servlets VI ....................... Luis Fernando Llana Dı́az Java Servlets 26 Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets VII <? xml version = " 1.0 " encoding = " ISO -8859 -1 " ? > <! DOCTYPE web - app PUBLIC " -// Sun Microsystems , Inc .// DTD Web Application 2.3// EN " " http: // java . sun . com / dtd / web - app_2_3 . dtd " > <web - app > < display - name > Filósofos </ display - name > < filter > < filter - name > envoltorio </ filter - name > < filter - class > EnvoltorioHTML </ filter - class > < init - param > < param - name > titulo </ param - name > < param - value > Filósofos </ param - value > </ init - param > </ filter > < filter > < filter - name > loginSesion </ filter - name > < filter - class > Login </ filter - class > </ filter > < filter > < filter - name > MierdaExplorer </ filter - name > < filter - class > soporte . servlet . MierdaExplorer </ filter - class > 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 Los filósofos con servlets VIII </ filter > < filter - mapping > < filter - name > envoltorio </ filter - name > <url - pattern >/ http / filosofo </ url - pattern > </ filter - mapping > < filter - mapping > < filter - name > MierdaExplorer </ filter - name > <url - pattern >/ http /* </ url - pattern > </ filter - mapping > < filter - mapping > < filter - name > loginSesion </ filter - name > <url - pattern >/ http / filosofo </ url - pattern > </ filter - mapping > < servlet > < servlet - name > filosofo </ servlet - name > < servlet - class > Filosofo </ servlet - class > </ 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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets IX <url - pattern >/ servlet /* </ url - pattern > </ servlet - mapping > </ web - app > Luis Fernando Llana Dı́az 52 53 54 Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Java Servlets Los filósofos con servlets X 1 2 3 private static boolean esIE ( H t t p S e rv l e t R e q u e s t req ) { 4 String userAgent = req . getHeader ( " user - agent " ); 5 return userAgent . toLowerCase (). indexOf ( " msie " ) >0; 6 } 7 8 public final void doFilter ( final ServletRequest _request , 9 final ServletResponse response , 10 final FilterChain filterChain ) 11 throws IOException , Se rvle tExc epti on { 12 H t t p S e rv l e t R e q u e s t request = ( H t t p S e rv l e t R e q u e s t ) _request ; 13 H t t p S e r v l e t R e s p o n s e responseString 14 = new ResponseString (( H t t p S e r v l e t R e s p o n s e ) response ); 15 S e r v l e t O u t p u t S t r e a m out = responseString . getOu tp ut S t re a m (); 16 Enumeration nombres = request . getHeaderNames (); 17 if ( esIE ( request )) { 18 ServletContext ctx = config . g et Se r vl et C on t e x t (); 19 out . println ( Tags . script ( " " , IncluyeFicher o . incluye ( ctx . getRealPath ( javaScript 20 )))); out . println ( Tags . p ( " " ," Mierda de explorer " )); 21 } else { 22 out . println ( Tags . p ( " " ," Menos mal que es un navegador decente " )); 23 } 24 filterChain . doFilter ( request , responseString ); 25 public class MierdaExplorer implements Filter { private static String javaScript = " javaScript / mierdaExp lor er . js " ; Luis Fernando Llana Dı́az Java Servlets Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets XI out = response . ge tOutputStream (); 26 String res = responseString . toString (); 27 if ( esIE ( request )) { 28 res = reemplazaBoton ( res ); 29 } 30 out . println ( res ); 31 if ( esIE ( request )) { 32 out . println ( Tags . p ( Tags . clase ( " disclaimer " ) , " This pages require an HTML 334.01 compliant navigator . Unfortunately Internet Explorer is not , thus we do not guarantee their correct behavior } 34 35 } 36 37 public static String reemplazaBoton ( String codigo ) { 38 Pattern p = Pattern . compile ( " < button * name =\"([^\"]*)\" * " + 39 " type =\"([^\"]*)\" * " + 40 " value =\"([^\"]*)\" * " + 41 " ([^ < >]*) >([^ < >]*) </ button > " ); 42 String res = codigo ; 43 Matcher m = p . matcher ( res ); 44 while ( m . find ()) { 45 String tipo = m . group (2); 46 String nombre = m . group (1); 47 String valor = m . group (3); 48 String attrExtra = m . group (4); 49 String texto = m . group (5); 50 String nuevo = 51 Luis Fernando Llana Dı́az Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Java Servlets Los filósofos con servlets XII } Tags . input ( " " , nombre , Tags . type ( tipo )+ 52 Tags . value ( texto )+ 53 Tags . attribute ( " onclick " ," cambiaValor ( this , ’ " + valor + " ’) "54 )+ attrExtra ); 55 res = m . replaceFirst ( nuevo ); 56 m = p . matcher ( res ); 57 } 58 return res ; 59 } 60 61 private FilterConfig config ; 62 public void init ( FilterConfig filterConfig ) throws S e rv l e t E x c e p t i o n { 63 config = filterConfig ; 64 } 65 66 public void destroy () { 67 config = null ; 68 } 69 70 Luis Fernando Llana Dı́az Java Servlets Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid Los filósofos con servlets XIII public class ResponseString extends H t t p S e r v l e t R e s p o n s e W r a p p e r { private S t r i n g Ou t p u t S t r e a m out ; public ResponseS tring ( H t t p S e r v l e t R e s p o n s e response ) { super ( response ); out = new S t r i n g Ou t p u t S t r e a m (); } public S e r v l e t O u t p u t S t r e a m getOutputStream () { return out ; } public String toString () { return out . toString (); } } Luis Fernando Llana Dı́az 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 Java Servlets Los filósofos con servlets XIV class S t r i n g Ou t p u t S t r e a m extends S e r v l e t O u t p u t S t r e a m { private B y t e A r r a y O u t p u t S t r e a m array ; public S t r i n g Ou t p u t S t r e a m () { array = new B y t e A r r a y O u t p u t S t r e a m (); } public void write ( int b ) { array . write ( b ); } public String toString () { try { return array . toString ( " iso -8859 -15 " ); } catch ( Exception e ) { throw new Ru ntim eExc epti on ( e . getMessage () , e ); } } } 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