Documente Academic
Documente Profesional
Documente Cultură
14 de mayo de 2007
Marcas espciales: < % cdigo Java %> o < %=expresin %> o Variable predenida request.
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 .*;
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 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
< 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
< 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
< %@ 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
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
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
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
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
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
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.
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
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
Un JavaBean es un objeto de una clase cuyos mtodos pblicos e u son de la forma getXXXX o setXXXX.
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 ; }
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 ; }
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
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
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
Rellena los el JavaBean con los parmetros del request, si no hay a no hace nada.
< jsp : setProperty name = " valor " property = " * " / > 1
2 3
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
Qu hace falta? e Fichero de descripcin de las etiquetas .tld. o Un manejador que implementa lo que quiero hacer con mis etiquetas.
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
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
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.
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).
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
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 (); }
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
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
< %@ 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
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
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
< 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