Sunteți pe pagina 1din 46

JSP: Java Server Pages

Luis Fernando Llana D az


Departamento de Sistemas Informticos y Computacin a o Universidad Complutense de Madrid

14 de mayo de 2007

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Java Server Pages


Java empotrado dentro de HTML.
< html > < body > <% String nombre = request . getParameter ( " nombre " ); if ( nombre == null ) { nombre = " Mundo " ; } %> <p > Hola < %= nombre %> </ p > </ body > </ html > 1 2 3 4 5 6 7 8 9 10 11

Marcas espciales: < % cdigo Java %> o < %=expresin %> o Variable predenida request.

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Traduccin a servlet I o

1 2 3 4 5 public class pr1_jsp extends HttpJspBase { 6 7 private static java . util . Vector _jspx_includes ; 8 9 public java . util . List getIncludes () { 10 return _jspx_includes ; 11 } 12 13 public void _jspService ( 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 )14 throws java . io . IOException , Se rvle tExc epti on { 15 /* Cuerpo del m todo que que realiza el servicio */ e 16 } 17 } 18 import import import import javax . servlet .*; javax . servlet . http .*; javax . servlet . jsp .*; org . apache . jasper . runtime .*;

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Traduccin a servlet II o

public void _jspService ( 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 )1 throws java . io . IOException , Se rvle tExc epti on { 2 JspFactory _jspxFactory = null ; 3 javax . servlet . jsp . PageContext pageContext = null ; 4 HttpSession session = null ; 5 Se rv letContext application = null ; 6 ServletConfig config = null ; 7 JspWriter out = null ; 8 Object page = this ; 9 JspWriter _jspx_out = null ; 10 try { 11 _jspxFactory = JspFactory . g et De f au lt F ac t or y (); 12 response . setContentType ( " text / html ; charset = ISO -8859 -1 " ); 13 pageContext = _jspxFactory . getPageContext ( this , request , response , null , true 14 819 , application = pageContext . g et Se r vl et C on t ex t (); 15 config = pageContext . ge tSer vlet Conf ig (); 16 session = pageContext . getSession (); 17 out = pageContext . getOut (); 18 _jspx_out = out ; 19 /* T r a d u c c i n de la p gina */ o a 20 } catch ( Throwable t ) { 21 out = _jspx_out ; 22 if ( out != null && out . getBufferSize () != 0) out . clearBuffer (); 23 if ( pageContext != null ) pageContext . h a n d l e P a g e E x c e p t i o n ( t ); 24 } finally { 25 if ( _jspxFactory != null ) _jspxFactory . r e l e a s eP a g e C o n t e x t ( pageContext ); 26 } 27 Luis Fernando Llana D az Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Traduccin a servlet III o

Traduccin de la pgina o a

out . write ( " <! - - $Id : transparencias . tex , v 1.3 2007 -05 -14 17:14:33 luis Exp $ 1 - >\ n out . write ( " < html >\ n " ); 2 out . write ( " < body >\ n " ); 3 4 String nombre = request . getParameter ( " nombre " ); 5 if ( nombre == null ) { 6 nombre = " Mundo " ; 7 } 8 9 out . write ( " \ n " ); 10 out . write ( " <p > Hola " ); 11 out . print ( nombre ); 12 out . write ( " </p >\ n " ); 13 out . write ( " </ body >\ n " ); 14 out . write ( " </ html > " ); 15

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

< html > <! - - $Id : transparencias . tex , v 1.3 2007 -05 -14 17:14:33 luis Exp $ --> < body > <% int numero ; try { numero = Integer . parseInt ( request . getParameter ( " numero " )); } catch ( N u m b e r F o r m a t E x c e p t i o n e ) { numero =1; } %> < table > <% for ( int i = 1; i <= 10 ; i ++) { %> <tr > < td >< %= i %></td > < td >< %= numero %></td > < td >< %= i * numero %></td > </ tr > <% } %> </ table >

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

< table > <% for ( int i = 1; i <= 10; i ++) { out . print ( " <tr > " ); out . print ( " <td > " + i + " </ td > " ); out . print ( " <td > " + numero + " </ td > " ); out . print ( " <td > " +( i * numero )+ " </ td > " ); out . println ( " </ tr > " ); } %> </ table > </ body > </ html >

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Directivas: < %@ directiva atributos %> I


< html > < body > < %@ page import = " java . util . Date " %> < %@ page import = " java . text . DateFormat " %> < %@ page import = " java . text . Sim ple Date Form at " %> <% Date date = new Date (); DateFormat df = new Simp leDa teF orma t ( " dd de MMMM de yyyy " ); %> <p > Hoy es < %=df . format ( date ) %> </ p > </ body > </ html > 1 2 3 4 5 6 7 8 9 10 11 12 13

< %@ include file = " jsp / cabecera . jsp " %> < h1 > Cap tulo 1 </ h1 > < %@ include file = " html / capitulo1 . html " < h1 > Cap tulo 2 </ h1 > < %@ include file = " html / capitulo2 . html " < h1 > Cap tulo 3 </ h1 > < %@ include file = " html / capitulo3 . html " < h1 > Cap tulo 4 </ h1 > < %@ include file = " html / capitulo4 . html " < %@ include file = " html / pie . html " %>

%> %> %> %>

1 2 3 4 5 6 7 8 9 10

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Habichuelas Java: JavaBeans


< body > < jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / > < jsp : setProperty name = " valor " property = " * " / > <% if ( valor . getNombre ()== null || valor . getIbex_id ()== null || valor . getUrl ()== null || valor . getTipo ()==0 ) { String nombre = valor . getNombre ()== null ? " " : valor . getNombre (); String ibex_id = valor . getIbex_id ()== null ? " " : valor . getIbex_id (); String url = valor . getUrl ()== null ? " " : valor . getUrl (); int tipo = valor . getTipo ()==0?0: valor . getTipo (); %> < form action = " pr5 . jsp " method = " get " > <p > < label > Nombre : </ label > < input name = " nombre " value = " < %= nombre %>" > < br > < label > ibex_id : </ label > < input name = " ibex_id " value = " < %= ibex_id %>" > < br > < label > URL : </ label > < input name = " url " value = " < %= url %>" > < br > < label > Tipo </ label > < select name = " tipo " > < option value = " < %= Valor . ACCIONES %>" > Acciones </ option > < option value = " < %= Valor . FONDOS %>" > Fondos </ opcion > </ select > < button type = " submit " > Enviar </ button > </ p > </ form > < % } else { %> < jsp : getProperty name = " valor " property = " datos " / > < % } %> </ body > 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 Informticos y ComputacinUniversidad Complutense de Madrid a o

Etiquetas personalizadas I
< body > <%

1 2 String nombre = request . getParameter ( " nombre " ); 3 String ibex_id = request . getParameter ( " ibex_id " ); 4 String url = request . getParameter ( " url " ); 5 String strTipo = request . getParameter ( " tipo " ); 6 7 int tipo = strTipo == null ? 0: Integer . parseInt ( strTipo ); 8 if ( nombre == null || url == null || tipo ==0) { 9 %> 10 < form action = " pr6 . jsp " method = " get " > 11 <p > 12 < label > Nombre : </ label > < input name = " nombre " value = " < %= nombre == null ? " " : nombre %>" > <13 > br < label > Ibex ID : </ label > < input name = " ibex_id " value = " < %= ibex_id == null ? " " : ibex_id %>" > < b 14 < label > url : </ label > < input name = " url " value = " < %= url == null ? " " : url %>" > < br > 15 < label > Tipo : </ label > 16 < select name = " tipo " > 17 < option value = " < %= Valor . ACCIONES %>" > Acciones </ option > 18 < option value = " < %= Valor . FONDOS %>" > Fondos </ opcion > 19 </ select > 20 < br > 21 < button type = " submit " > Enviar </ button > 22 </ p > 23 </ form > 24 < % } else { %> 25

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Etiquetas personalizadas II

< % } else { %> 1 < %@ taglib uri = " xml / valores . tld " prefix = " valores " %> 2 < valores : repite ini = " 5 " fin = " 8 " > 3 < % if ( ibex_id == null || ibex_id . equals ( " " )) { %> 4 < valores : entrada nombre = " < %= nombre %>" url = " < %= url %>" tipo = " < %= tipo %>" / > 5 < % } else { %> 6 < valores : entrada nombre = " < %= nombre %>" ibex_id = " < %= ibex_id %>" url = " < %= url %>" tipo 7 " < %= = < % } %> 8 </ valores : repite > 9 <% } %> 10 </ body > 11

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Variables Predenidas
request El HttpServletRequest asociada con esta peticin. o response El HttpServletResponse asociada con esta peticin. o out El PrintWriter usado para mandar la salida al usuario. session El HttpSession asociada con esta peticin. Las o sesiones estn activadas por defecto. Recordemos el a mtodo response.encodeURL. e application El ServletContext del servlet. config El ServletConfig del servlet. pageContext Un objeto de clase PageContext para encapsular ciertas caracter sticas de los JSP. page El objeto que respresenta al sevlet: this.
Luis Fernando Llana D az Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Sesin o

< body > 1 <% 2 if ( request . getParameter ( " borrarSesion " )!= null ) { 3 session . removeAttribute ( " num " ); 4 } 5 Integer num =( Integer ) session . getAttribute ( " num " ); 6 if ( num == null ) { 7 num = new Integer (0); 8 } 9 num = new Integer ( num . intValue ()+1); 10 session . setAttribute ( " num " , num ); 11 %> 12 <p > Has accedido < %=num . intValue () % > veces a la p gina </ p > a 13 < form action = " pr7 . jsp " > 14 <p > < button name = " borrarSesion " type = " submit " > Borrar Sesi n </ button > </ p > o 15 <p > < button name = " conti nu ar Se si on " type = " submit " > Continuar Sesi n </ button > </ p >16 o </ form > 17 </ body > 18

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Directivas page
Atributos: import Las clusulas import debe haber en el servlet. a
< %@ page import = " java . util .* " %> < %@ page import = " java . text . DateFormat " %> < %@ page import = " java . text . Sim ple Date Form at " %> 1 2 3

contentType Especica el tipo MIME:


< %@ page contentType = " text / html ; charset = iso -8859 -15 " %> 1

session Valor true (por defecto) usa sesiones, valor false no. extends Qu debe extender el servlet. e info La cadena que se obtiene a travs del mtodo e e getServletInfo.
Luis Fernando Llana D az Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Directivas page
Atributos: isThreadSafe Valor true (por defecto) es un servlet normal, el valor false indica que el servlet implementa SingleThreadModel. buffer Especica el tamao del JspWriter. Por defecto n toma el valor que se especica en el servidor. autoflush Valor true (por defecto) indica que el buer es ushed cuando est lleno, a si tiene el valor false se provoca una excepcin. o errorPage Pgina JSP que procesa las exceptions. a isErrorPage Indica si la pgina es de error o no. a language El unico valor posible el Java
Luis Fernando Llana D az Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Directivas include

Incluye una pgina en tiempo de compilacin a o


< %@ include file = " jsp / pie . jsp " %> 1

Pueden incluir HTML esttico y marcas JSP. a

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Acciones JSP
Las acciones JSP usan sintaxis XML para controlar el comportamiento del servlent: jsp:include Incluye una pgina en tiempo de ejecucin. a o jsp:useBean Usa una habichuela de Java. jsp:setProperty Pone una propiedad de una habichuela de Java. jsp:getProperty Consulta una propiedad de una habichuela de Java. jsp:forward Dirige la peticin a otra pgina. o a jsp:plugin Genera las etiquetas para el plugin de JAVA para el navegador.

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Accin jsp:include I o
< jsp : include page = " jsp / cabecera . jsp " / > < h1 > Cap tulo 1 </ h1 > < jsp : include page = " html / capitulo1 . html " < h1 > Cap tulo 2 </ h1 > < jsp : include page = " html / capitulo2 . html " < h1 > Cap tulo 3 </ h1 > < jsp : include page = " html / capitulo3 . html " < h1 > Cap tulo 4 </ h1 > < jsp : include page = " html / capitulo4 . html " < %@ include file = " jsp / pie . jsp " %> 1 2 3 4 5 6 7 8 9 10

/> /> /> />

out . write ( " <! - - $Id : transparencias . tex , v 1.3 2007 -05 -14 17:14:33 luis Exp $ 1 - >\ n J s p Ru n ti me L ib r ar y . include ( request , response , " html / cabecera . html " , out , false 2 ); out . write ( " \ n " ); 3 out . write ( " <h1 > Cap tulo 1 " ); 4 out . write ( " </ h1 >\ n " ); 5 J s p Ru n ti me L ib r ar y . include ( request , response , " html / capitulo1 . html " , out , false ); 6 out . write ( " \ n " ); 7 out . write ( " <h1 > Cap tulo 2 " ); 8 out . write ( " </ h1 >\ n " ); 9 J s p Ru n ti me L ib r ar y . include ( request , response , 10 " html / capitulo2 . html " , out , false ); 11 12 /* Resto de la t r a d u c c i n */ o 13

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Accin jsp:include II o

Date date = new Date (); DateFormat df = new Si mple Date Form at ( " dd de MMMM de yyyy " ); out . write ( " \ n " ); out . write ( " <p > " ); out . print ( df . format ( date )); out . write ( " </p >\ n " ); out . write ( " </ body >\ n " ); out . write ( " </ html >\ n " ); out . write ( " \ n " );

1 2 3 4 5 6 7 8 9 10

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java

Un JavaBean es un objeto de una clase cuyos mtodos pblicos e u son de la forma getXXXX o setXXXX.

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java I


public class Valor public public public public private private private private final final final final extends TagSupport { int ACCIONES =1; int FONDOS =2; String strAcciones = " acciones " ; String strFondos = " fondos " ; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

static static static static

String nombre = null ; String ibex_id = null ; int tipo =0; String url = null ;

public Valor () { super (); } public void setNombre ( String _nombre ) { nombre = _nombre ; } public String getNombre () { return nombre ; }

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java II


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

public void setIbex_id ( String _ibex_id ) { ibex_id = _ibex_id ; } public String getIbex_id () { return ibex_id ; } public void setUrl ( String _url ) { url = _url ; } public String getUrl () { return url ; } public void setTipo ( int _tipo ) { tipo = _tipo ; } public int getTipo () { return tipo ; }

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java III


public String getDatos () { StringBuffer out = new StringBuffer (); out . append ( " <dl >\ n " ); out . append ( " <dt > Nombre < dd > < a href =\ " " + url + " \ " >" + nombre + " </a > " ); out . append ( " <dt > Apellidos < dd > " + ibex_id ); out . append ( " <dt > Tipo < dd > " +( tipo ==1? " acciones " : " fondos " )); out . append ( " </ dl >\ n " ); return out . toString (); }

1 2 3 4 5 6 7 8 9 10 11 public static int parse ( String s ) { 12 if ( s . equals ( strAcciones )) { 13 return ACCIONES ; 14 } else if ( s . equals ( strFondos )) { 15 return FONDOS ; 16 } else { 17 throw new T i p o V a l o r E x c e p t i o n ( " La cadena " + s + " no representa un tipo de val 18 } 19 20 } 21 public final int doStartTag () throws JspException { 22 .......................... 23 } 24 25

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java


Indicar que se va a usar un JavaBean
< jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / > 1

id El nombre que le damos al objeto scope El mbido donde vive el objeto a request Vlido para el request. Valor por a defecto session Vlido para la sesin. a o application Vlido para todas pginas que a a comparten el ServletContext. class La clase que dene el JavaBean type El tipo esttico (la clase o una superclase suya). a
Luis Fernando Llana D az Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java

Dar valores a los campos del JavaBean. El normal, pone el valor que se indique
< jsp : useBean id = " nombre " ... / > ... < jsp : setProperty name = " nombre " property = " propiedad " ... / > 1 2 3 4

Slo da el valor si construye el objeto. o


< jsp : useBean id = " myName " ... > ... < jsp : setProperty name = " myName " property = " someProperty " ... / > </ jsp : useBean > 1 2 3 4 5

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java


El jsp:setProperty puede tener los siguientes atributos: name Usa el JavaBean cuyo id se indique. property Indica el nombre de la propiedad que se quiera poner. a El valor * indica los parmetros del request que case con algn setXXXX del JavaBean. u value (Opcional) el valor que se da la propiedad. param (Opcional) el valor se toma del parmetro de request a que se indica. Si no existe tal parmetro no se hace a nada. Se pueden omitir tanto value como param, entonces el valor se toma del parmetro del request cuyo nombre es property. a

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java


Invoca al mtodo elAgenda.setNombre("Patata"). e
< jsp : setProperty name = " valor " property = " nombre " value = " Patata " / > 1

Si request.getParameter("patata") no es null, llama a valor.setNombre(request.getParameter("patata")).


< jsp : setProperty name = " valor " property = " nombre " value = " patata " / > 1

Si request.getParameter("nombre") no es null, llama a valor.setNombre(request.getParameter("nombre")).


< jsp : setProperty name = " valor " property = " nombre " / > 1

Rellena los el JavaBean con los parmetros del request, si no hay a no hace nada.
< jsp : setProperty name = " valor " property = " * " / > 1

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java

Acceder valores a los campos del JavaBean.


< dl > < dt > Nombre </ dt > < dd > <a href = < jsp : getProperty name = " valor " property = " url " / > > < jsp : getProperty name = " valor " property = " nombre " / > </ a > </ dd > < dt > Ibex ID </ dt > < dd > < jsp : getProperty name = " valor " property = " ibex_id " / > </ dd > < dt > Tipo </ dt > < dd > < jsp : getProperty name = " valor " property = " strTipo " / > </ dd > </ dl > 1 2 3 4 5 6 7 8

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Las habichuelas Java


< body > < jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / > < jsp : setProperty name = " valor " property = " * " / > <% if ( valor . getNombre ()== null || valor . getIbex_id ()== null || valor . getUrl ()== null || valor . getTipo ()==0 ) { String nombre = valor . getNombre ()== null ? " " : valor . getNombre (); String ibex_id = valor . getIbex_id ()== null ? " " : valor . getIbex_id (); String url = valor . getUrl ()== null ? " " : valor . getUrl (); int tipo = valor . getTipo ()==0?0: valor . getTipo (); %> < form action = " pr5 . jsp " method = " get " > <p > < label > Nombre : </ label > < input name = " nombre " value = " < %= nombre %>" > < br > < label > ibex_id : </ label > < input name = " ibex_id " value = " < %= ibex_id %>" > < br > < label > URL : </ label > < input name = " url " value = " < %= url %>" > < br > < label > Tipo </ label > < select name = " tipo " > < option value = " < %= Valor . ACCIONES %>" > Acciones </ option > < option value = " < %= Valor . FONDOS %>" > Fondos </ opcion > </ select > < button type = " submit " > Enviar </ button > </ p > </ form > < % } else { %> < jsp : getProperty name = " valor " property = " datos " / > < % } %> </ body > 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 Informticos y ComputacinUniversidad Complutense de Madrid a o

Taglibs denidas por el usuario

La sintaxis de las acciones jsp es XML


< jsp:useBean id = " valor " scope = " request " class = " valores . Valor " / > < j s p:setProperty name = " valor " property = " * " / > 1 2

2 3

El XML mola mucho La implementacin de los servlets es Software Libre o

Por qu no puedo hacerlo yo para mis propias aplicaciones? e Por qu no puedo denir algo como? e
< valores : entrada nombre = " < %= nombre %>" idex_id = " < %= apellidos %>" tipo = " < %= tipo %>" / > 1 2

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Taglibs denidas por el usuario

Qu hace falta? e Fichero de descripcin de las etiquetas .tld. o Un manejador que implementa lo que quiero hacer con mis etiquetas.

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Ficheros tld
Es un chero XML
<? xml version = " 1.0 " encoding = " iso -8859 -1 " ? > <! DOCTYPE taglib PUBLIC " -// Sun Microsystems , Inc .// DTD JSP Tag Library 1.2// EN " " http: // java . sun . com / dtd / web - j sp ta g li b ra ry _ 1_ 2 . dtd " > < taglib > < tlib - version > 1.0 </ tlib - version > <jsp - version > 1.2 </ jsp - version > < short - name > Valor </ short - name > < tag > < name > entrada </ name > <tag - class > valores . Valor </ tag - class > < body - content > empty </ body - content > < attribute > < name > nombre </ name > < required > true </ required > < rtexprvalue > true </ rtexprvalue > </ attribute > <! -- m s a t r i b u t o s -- > a </ tag > <! -- m s marcas tag -- > a </ taglib > 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Ficheros tld

Las etiquetas de la cabecera son todas opcionales, menos: tlib-version Versin de la librer o a. jsp-version Versin de JSP de la que depende. o short-name Nombre corto. Puede ser usado por las aplicaciones como prejo preferido. El resto de las marcas son uri, display-name, small-icon, large-icon, description, validator, listener. Luego puede haber una o ms marcas tag. a

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Ficheros tld. Marca tag

name nombre de la etiqueta tag-class la clase (manejador) que implementa la etiqueta. body-content Puede tomar los valores JSP El contenido es JSP que se debe interpretar. tagdependent El contenido est en otro lenguaje, a por ejemplo SQL. empty No tiene cuerpo.

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Ficheros tld. Marca tag

attribute Los atributos que puede tener, Contiene las siguientes marcas: name el nombre del atributo required el el atributo es opcional o no (true o false). rtexprvalue si el contenido es esttico o no (true a o false).

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags sin cuerpo I


javax.servlet.jsp.tagext.Tag javax.servlet.jsp.tagext.TagSupport
1

Inicializacin o setPageContext(), setParent(), los setXXXX. doStartTag() que devuelve SKIP_BODY (si no hay cuerpo) o EVAL_BODY_INCLUDE. doEndTag() que devuelve EVAL_PAGE o SKIP_PAGE

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags sin cuerpo II


package valores ; import javax . servlet . jsp . tagext . TagSupport ; import javax . servlet . jsp . JspException ; import javax . servlet . jsp . JspWriter ; import java . io . IOException ; public class Valor extends TagSupport { private private private private String nombre = null ; String ibex_id = null ; int tipo =0; String url = null ; 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22

public final String getNombre () { return nombre ; } public final void setNombre ( final String newNombre ) { this . nombre = newNombre ; } /* m s getters y setters */ a public Agenda () { super (); }

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags sin cuerpo III

public final int doStartTag () throws JspException { JspWriter out = pageContext . getOut (); try { out . write ( " <dl >\ n " ); out . write ( " <dt > Nombre < dd > < a href =\" " + url + " \" > " + nombre + " </a > " ); if ( ibex_id != null ) { out . write ( " <dt > Ibex ID < dd > " + ibex_id ); } out . write ( " <dt > Tipo < dd > " +( tipo == ACCIONES ? strAcciones : strFondos )); out . write ( " </ dl >\ n " ); } catch ( IOException e ) { throw new JspException ( " IO exception " + e . getMessage () , e ); } return super . E VA L_ B OD Y_ I N C L UD E ; } }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo I


javax.servlet.jsp.tagext.BodyTag javax.servlet.jsp.tagext.BodyTagSupport
1 Inicializacin setPageContext(), o

setParent(), los setXXXX.


2 doStartTag() que devuelve

SKIP_BODY (si no hay cuerpo) o EVAL_BODY_INCLUDE, EVAL_BODY_BUFFERED, 3 doInitBody(), setBodyContent(). 4 doAfterBody una o ms veces. a Devuelve EVAL_BODY_AGAIN para evaluar otra vez o SKIP_BODY para nalizar. 5 doEndTag() que devuelve EVAL_PAGE o SKIP_PAGE
Luis Fernando Llana D az Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo II

< %@ taglib uri = " xml / valores . tld " prefix = " valores " %> 1 < va lo res :repite ini = " 5 " fin = " 8 " > 2 < % if ( ibex_id == null || ibex_id . equals ( " " )) { %> 3 < v a l o r es:entrada nombre = " < %= nombre %>" url = " < %= url %>" tipo = " < %= tipo %>" / > 4 < % } else { %> 5 < v a l o r es:entrada nombre = " < %= nombre %>" ibex_id = " < %= ibex_id %>" url = " < %= url %>" tipo 6 " < %= = < % } %> 7 </ v al ore s:repite > 8

< tag > < name > repite </ name > <tag - class > valores . Repite </ tag - class > < body - content > JSP </ body - content > < attribute > < name > ini </ name > < required > true </ required > < rtexprvalue > true </ rtexprvalue > </ attribute > < attribute > < name > fin </ name > < required > true </ required > < rtexprvalue > true </ rtexprvalue > </ attribute > </ tag >

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo III

package valores ; import import import import javax . servlet . jsp . tagext . BodyTagSupport ; javax . servlet . jsp . JspException ; javax . servlet . jsp . tagext . BodyContent ; java . io . IOException ;

public class Repite extends BodyTagSupport { private int ini ; private int fin ; private int act ; /* getters and setters */ public final void doInitBody () throws JspException { act = ini ; }

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo IV


public final int doAfterBody () throws JspException { act ++; if ( act <= fin ) { return E V A L _ B OD Y _ B U F F E R E D ; } else { return SKIP_BODY ; } } public final int doEndTag () throws JspException { BodyContent body = getBodyContent (); try { body . writeOut ( pageContext . getOut ()); } catch ( IOException e ) { throw new JspException ( " IOException : " + e . getMessage () , e ); } return EVAL_PAGE ; } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Funciona bien con la siguiente?


< valores : repite ini = " 8 " fin = " 5 " > < valores : entrada nombre = " < %= nombre %>" ibex_id = " < %= ibex_id %>" tipo = " < %= tipo %>" / > </ valores : repite > Luis Fernando Llana D az 1 2 3 4

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo V


< valores : mysql - conexion database = " valores " host = " localhost " user = " luis " password = " patata " > < valores : busca ibex_id = " < %= ibex_id %>" / > </ valores : mysql - conexion > 1 2 3 4

La etiqueta valores:mysql-conexion construye la conexin o connection.


public final int doStartTag () throws JspException { try { Class . forName ( " com . mysql . jdbc . Driver " ). newInstance (); connection = DriverManager . getConnection ( " jdbc : mysql :// " + host + " / " + database + " ? user = " + user + " & password = " + password ); } catch ( Exception e ) { throw new JspException ( " Excepci n " + e . getClass (). getName ()+ o " " + e . getMessage () , e ); } return E V A L _ B OD Y _ B U F F E R E D ; } 1 2 3 4 5 6 7 8 9 10 11 12

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo VI

public final int doEndTag () throws JspException { try { BodyContent body = getBodyContent (); body . writeOut ( pageContext . getOut ()); connection . close (); } catch ( Exception e ) { throw new JspException ( " Excepci n o " + e . getClass (). getName ()+ " : " + e . getMessage () , e ); } return EVAL_PAGE ; }

1 2 3 4 5 6 7 8 9 10 11 12 13

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Tags con cuerpo VII


La clase que implementa valores:mysql-conexion tiene el getConnection(). La clase que implementa la bsqueda debe u acceder a ella.
public final int doEndTag () throws JspException { try { Conexion conexion = ( Conexion ) f i n d A n c e s t o r W i t h C l a s s ( this , Class . forName ( " valores . Conexion " )); Connection con = conexion . getConnection (); String sql = " select * from valores " + " where ibex_id like %" + ibex_id + " %" ; P re pa r ed St a te m en t psmt = con . pr epar eSta teme nt ( sql ); ResultSet rs = psmt . executeQuery (); JspWriter out = pageContext . getOut (); out . write ( " <p > Resultados </ p > " ); /* Se muestran los r e s u l t a d o */ } catch ( Exception e ) { throw new JspException ( " Excepci n " + e . getClass (). getName ()+ o " : " + e . getMessage () , e ); } return EVAL_PAGE ; } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

Jakarta Taglibs http://jakarta.apache.org/taglibs/index.html


Proyecto de Software libre en la que se implementan diversas taglibs: Librer estndar de etuquetas JSLT. a a
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSTL.html
< c:forEach var = " item " items = " ${ sessionScope . cart . items } " > ... </ c:forEach > 1 2 3

< c:set var = " bookId " value = " ${ param . Remove } " / > < jsp:useBean id = " bookId " type = " java . lang . String " / > < % cart . remove ( bookId ); %> < sql:query var = " books " dataSource = " ${ appl icat ionS cope . bookDS } " > select * from PUBLIC . books where id = ? < sql:param value = " ${ bookId } " / > </ sql:query >

1 2 3 4 5 6 7 8

Luis Fernando Llana D az

Departamento de Sistemas Informticos y ComputacinUniversidad Complutense de Madrid a o

S-ar putea să vă placă și