Download JSP: Java Server Pages - Universidad Complutense de Madrid

Document related concepts
no text concepts found
Transcript
JSP: Java Server Pages
Luis Fernando Llana Dı́az
Departamento de Sistemas Informáticos y Computación
Universidad Complutense de Madrid
29 de abril de 2013
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Java Server Pages
Java empotrado dentro de HTML.
< %@ page pageEncoding = " utf -8 " %>
<%
String name = request . getParameter ( " name " );
if ( name == null ) {
name = " World " ;
}
%>
< html >
< body >
<p > Hello < %=name %> </ p >
< form action = " hello . jsp " >
< input name = " name " / >
< button > Send </ button >
</ form >
</ body >
</ html >
Marcas espciales:
< % Java code %>
< %= expression %>
Variable predefinida request.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Traducción a servlet I
Fichero:
${catalina.home}/work/Catalina/localhost/
hello-jsp/org/apache/jsp/jsp/hello_jsp.java
/*
* G e n e r a t e d by the Jasper c o m p o n e n t of Apache Tomcat
* Version : Apache Tomcat /7.0.37
* G e n e r a t e d at : 2013 -04 -17 07:12:55 UTC
* Note : The last modif ied time of this file was set to
*
the last modifi ed time of the source file after
*
g e n e r a t i o n to assist with m o d i f i c a t i o n tracking .
*/
package org . apache . jsp . jsp ;
import javax . servlet .*;
import javax . servlet . http .*;
import javax . servlet . jsp .*;
.....................
.....................
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Traducción a servlet II
public void _jspService ( final javax . servlet . http . H tt pS e rv l et Re q ue s t request , final jav
throws java . io . IOException , javax . servlet . ServletException {
final javax . servlet . jsp . PageContext pageContext ;
javax . servlet . http . HttpSession session = null ;
final javax . servlet . ServletContext application ;
final javax . servlet . ServletConfig config ;
javax . servlet . jsp . JspWriter out = null ;
final java . lang . Object page = this ;
javax . servlet . jsp . JspWriter _jspx_out = null ;
javax . servlet . jsp . PageContext _j s px _ pa ge _ co n te xt = null ;
. . . . . . . . . . . . . . . .. . .
. . . . . . . . . .. .. . .. . .
try {
response . setContentType ( " text / html ; charset = utf -8 " );
pageContext = _jspxFactory . getPageContext ( this , request , response ,
null , true , 8192 , true );
_ j s px _ pa g e_ co n te x t = pageContext ;
application = pageContext . ge tSe rvl etC ont ext ();
config = pageContext . getServletConfig ();
session = pageContext . getSession ();
out = pageContext . getOut ();
_jspx_out = out ;
..................................
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Traducción a servlet III
..................................
..................................
} catch ( java . lang . Throwable t ) {
if (!( t instanceof javax . servlet . jsp . S kipP age Exc ept ion )){
out = _jspx_out ;
if ( out != null && out . getBufferSize () != 0)
try { out . clearBuffer (); } catch ( java . io . IOException e ) {}
if ( _ js p x_ pa g e_ co n te x t != null ) _ js px _ pa g e_ co n te xt . h a n d l e P ag e E x c e p t i o n ( t );
else throw new ServletException ( t );
}
} finally {
_jspxFactory . r e le as e Pa ge C on t ex t ( _ j sp x_ p ag e _c on t ex t );
}
}
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Traducción a servlet IV
Traducción de la página
out . write ( " \ n " );
out . write ( " \ n " );
out . write ( " \ n " );
out . write ( " < html >\ n " );
out . write ( " < body >\ n " );
String name = request . getParameter ( " name " );
if ( name == null ) {
name = " World " ;
}
out . write ( " \ n " );
out . write ( " <p > Hello " );
out . print ( name );
out . write ( " </p >\ n " );
out . write ( " < form action =\" hello . jsp \" >\ n " );
out . write ( " < input name =\" name \"/ >\ n " );
out . write ( " < button > Send </ button >\ n " );
out . write ( " </ form >\ n " );
out . write ( " </ body >\ n " );
out . write ( " </ html >
\ n " );
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Sensible al código spaghetti I
< %@ page pageEncoding = " utf -8 " %>
<%
String strNum = request . getParameter ( " number " );
if ( strNum != null ) {
int num = Integer . parseInt ( strNum );
%>
< table >
<%
for ( int i =0; i <10; i ++){
%>
< tr > < td > < %= num %> </ td > < td >x < %= i %> </ td > < td >= < %= num * i %> </ td > </ tr >
< %} %>
</ table >
< % } %>
< form action = " mult1 . jsp " >
< label > Number : </ label > < input size = " 2 " name = " number " >
< button > Submit </ button >
</ form >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Sensible al código spaghetti II
< %@ page pageEncoding = " utf -8 " %>
<%
String strNum = request . getParameter ( " number " );
if ( strNum != null ) {
int num = Integer . parseInt ( strNum );
%>
< table >
<%
for ( int i =0; i <10; i ++) {
out . println ( String . format ( " <tr > < td > %d </ td > < td > x %d = </ td > < td > %d </ td > " ,
num , i , num * i ));
}
%>
</ table >
< % } %>
< form action = " mult2 . jsp " >
< label > Number : </ label > < input size = " 2 " name = " number " >
< button > Submit </ button >
</ form >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Directivas: < %@ directiva atributos %>
< html >
< body >
< %@ page import = " java . util . Date " %>
< %@ page import = " java . text . DateFormat " %>
< %@ page import = " java . text . SimpleDateFormat " %>
<%
Date date = new Date ();
DateFormat df = new SimpleDateFormat ( " dd ’ de ’ MMMM ’ de ’ yyyy " );
%>
<p > Hoy es < %=df . format ( date) %> </ p >
</ body >
</ html >
< %@ include file = " jsp / cabecera . jsp " %>
< h1 >ı́Captulo 1 </ h1 >
< %@ include file = " html / capitulo1 . html "
< h1 >ı́Captulo 2 </ h1 >
< %@ include file = " html / capitulo2 . html "
< h1 >ı́Captulo 3 </ h1 >
< %@ include file = " html / capitulo3 . html "
< h1 >ı́Captulo 4 </ h1 >
< %@ include file = " html / capitulo4 . html "
< %@ include file = " html / pie . html " %>
Luis Fernando Llana Dı́az
JSP: Java Server Pages
%>
%>
%>
%>
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
JSP: Java Server Pages
Etiquetas personalizadas I
< body >
<%
String
String
String
String
nombre = request . getParameter ( " nombre " );
ibex_id = request . getParameter ( " ibex_id " );
url = request . getParameter ( " url " );
strTipo = request . getParameter ( " tipo " );
int tipo = strTipo == null ? 0: Integer . parseInt ( strTipo );
if ( nombre == null || url == null || tipo ==0) {
%>
< form action = " pr6 . jsp " method = " get " >
<p >
< label > Nombre : </ label > < input name = " nombre " value = " < %= nombre == null ? " " : nombre %>" > < br >
< label > Ibex ID : </ label > < input name = " ibex_id " value = " < %= ibex_id == null ? " " : ibex_id %>" > < b
< label > url : </ label > < input name = " url " value = " < %= url == null ? " " : url %>" > < br >
< label > Tipo : </ label >
< select name = " tipo " >
< option value = " < %= Valor . ACCIONES %>" > Acciones </ option >
< option value = " < %= Valor . FONDOS %>" > Fondos </ opcion >
</ select >
< br >
< button type = " submit " > Enviar </ button >
</ p >
</ form >
< % } else { %>
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Etiquetas personalizadas II
< % } else { %>
< %@ taglib uri = " / WEB - INF / valores . tld " prefix = " valores " %>
< valores : repite ini = " 5 " fin = " 8 " >
< % if ( ibex_id == null || ibex_id . equals ( " " )) { %>
< valores : entrada nombre = " < %= nombre %>" url = " < %= url %>" tipo = " < %= tipo %>" / >
< % } else { %>
< valores : entrada nombre = " < %= nombre %>" ibex_id = " < %= ibex_id %>" url = " < %= url %>" tipo = " < %=
< % } %>
</ valores : repite >
<% }
%>
</ body >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Variables Predefinidas
request El HttpServletRequest asociada con esta petición.
response El HttpServletResponse asociada con esta
petición.
out El PrintWriter usado para mandar la salida al
usuario.
session El HttpSession asociada con esta petición. Las
sesiones están activadas por defecto. Recordemos el
método response.encodeURL.
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
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Sesión
< body >
<%
if ( request . getParameter ( " borrarSesion " )!= null ) {
session . removeAttribute ( " num " );
}
Integer num =( Integer ) session . getAttribute ( " num " );
if ( num == null ) {
num = new Integer (0);
}
num = new Integer ( num . intValue ()+1);
session . setAttribute ( " num " , num );
%>
<p > Has accedido < %=num . intValue () % > veces a la ápgina </ p >
< form action = " pr7 . jsp " >
<p > < button name = " borrarSesion " type = " submit " > Borrar óSesin </ button > </ p >
<p > < button name = " continuarSesion " type = " submit " > Continuar óSesin </ button > </ p >
</ form >
</ body >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Directivas page
Atributos:
import Las cláusulas import debe haber en el servlet.
< %@ page import = " java . util .* " %>
< %@ page import = " java . text . DateFormat " %>
< %@ page import = " java . text . SimpleDateFormat " %>
contentType Especifica el tipo MIME:
< %@ page contentType = " text / html ; charset = utf -8 " %>
session Valor true (por defecto) usa sesiones,
valor false no.
extends La clase que debe extender el servlet.
info La cadena que se obtiene a través del método
getServletInfo.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Directivas page
Atributos:
isThreadSafe Valor true (por defecto) es un servlet normal,
el valor false indica que el servlet implementa
SingleThreadModel.
buffer Especifica el tamaño del JspWriter. Por defecto
toma el valor que se especifica en el servidor.
autoflush Valor true (por defecto) indica que el buffer es
flushed cuando está lleno,
si tiene el valor false se provoca una excepción.
errorPage Página JSP que procesa las exceptions.
isErrorPage Indica si la página es de error o no.
language El único valor posible el Java
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Directivas include
Incluye una página en tiempo de compilación
< %@ include file = " jsp / pie . jsp " %>
Pueden incluir HTML estático y marcas JSP.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Acciones JSP
Las acciones JSP usan sintaxis XML para controlar el
comportamiento del servlent:
jsp:include Incluye una página en tiempo de ejecución.
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 petición a otra página.
jsp:plugin Genera las etiquetas para el plugin de JAVA para el
navegador.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Acción jsp:include I
< jsp : include page = " jsp / cabecera . jsp " / >
< h1 >ı́Captulo 1 </ h1 >
< jsp : include page = " html / capitulo1 . html "
< h1 >ı́Captulo 2 </ h1 >
< jsp : include page = " html / capitulo2 . html "
< h1 >ı́Captulo 3 </ h1 >
< jsp : include page = " html / capitulo3 . html "
< h1 >ı́Captulo 4 </ h1 >
< jsp : include page = " html / capitulo4 . html "
< %@ include file = " jsp / pie . jsp " %>
/>
/>
/>
/>
out . write ( " <! - - $Id : transparencias . tex , v 1.3 2007 -05 -14 17:14:33 luis Exp $ - - >\ n
J s p Ru nti meLi bra ry . include ( request , response , " html / cabecera . html " , out , false );
out . write ( " \ n " );
out . write ( " <h1 >ı́Captulo 1 " );
out . write ( " </ h1 >\ n " );
J s p Ru nti meLi bra ry . include ( request , response , " html / capitulo1 . html " , out , false );
out . write ( " \ n " );
out . write ( " <h1 >ı́Captulo 2 " );
out . write ( " </ h1 >\ n " );
J s p Ru nti meLi bra ry . include ( request , response ,
" html / capitulo2 . html " , out , false );
/* Resto de la ó t r a d u c c i n */
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Acción jsp:include II
Date date = new Date ();
DateFormat df = new SimpleDateFormat ( " 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 " );
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Las habichuelas Java I
Un JavaBean es un objeto de una clase cuyos métodos públicos
son de la forma getXXXX o setXXXX.
public class Valor extends TagSupport {
public final static int ACCIONES =1;
public final static int FONDOS =2;
public final static String strAcciones = " acciones " ;
public final static String strFondos = " fondos " ;
private
private
private
private
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
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Las habichuelas Java II
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
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 ();
}
public static int parse ( String s ) {
if ( s . equals ( strAcciones )) {
return ACCIONES ;
} else if ( s . equals ( strFondos )) {
return FONDOS ;
} else {
throw new T ip oV a lo rE x ce p ti on ( " La cadena ’" + s + " ’ no representa un tipo de val
}
}
public final int doStartTag () throws JspException {
..........................
}
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Las habichuelas Java IV
Indicar que se va a usar un JavaBean
< jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / >
id El nombre que le damos al objeto
scope El ámbido donde vive el objeto
request Válido para el request. Valor por
defecto
session Válido para la sesión.
application Válido para todas páginas que
comparten el ServletContext.
class La clase que define el JavaBean
type El tipo estático (la clase o una superclase suya).
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 " ... / >
Sólo da el valor si construye el objeto.
< jsp : useBean id = " myName " ... >
...
< jsp : setProperty name = " myName "
property = " someProperty " ... / >
</ jsp : useBean >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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.
El valor * indica los parámetros del request que case
con algún setXXXX del JavaBean.
value (Opcional) el valor que se da la propiedad.
param (Opcional) el valor se toma del parámetro de request
que se indica. Si no existe tal parámetro no se hace
nada.
Se pueden omitir tanto value como param, entonces el valor se
toma del parámetro del request cuyo nombre es property.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Las habichuelas Java
Invoca al método elAgenda.setNombre("Patata").
< jsp : setProperty name = " valor " property = " nombre " value = " Patata " / >
Si request.getParameter("patata") no es null, llama a
valor.setNombre(request.getParameter("patata")).
< jsp : setProperty name = " valor " property = " nombre " value = " patata " / >
Si request.getParameter("nombre") no es null, llama a
valor.setNombre(request.getParameter("nombre")).
< jsp : setProperty name = " valor " property = " nombre " / >
Rellena los el JavaBean con los parámetros del request, si no hay
no hace nada.
< jsp : setProperty name = " valor " property = " * " / >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
JSP: Java Server Pages
Taglibs definidas por el usuario
1
La sintaxis de las acciones jsp es XML
< jsp:useBean id = " valor " scope = " request " class = " valores . Valor " / >
< j sp:setProperty name = " valor " property = " * " / >
2
El XML mola mucho
3
La implementación de los servlets es Software Libre
Por qué no puedo hacerlo yo para mis propias aplicaciones?
Por qué no puedo definir algo como?
< valores : entrada nombre = " < %= nombre %>"
idex_id = " < %= apellidos %>" tipo = " < %= tipo %>" / >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Taglibs definidas por el usuario
¿Qué hace falta?
Fichero de descripción de las etiquetas .tld.
Un manejador que implementa lo que quiero hacer con mis
etiquetas.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Ficheros tld
Es un fichero 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 spt agl ibr ary_ 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 >
<! -- áms a t r i b u t o s -- >
</ tag >
<! -- áms marcas tag -- >
</ taglib >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Ficheros tld
Las etiquetas de la cabecera son todas opcionales, menos:
tlib-version Versión de la librerı́a.
jsp-version Versión de JSP de la que depende.
short-name Nombre corto. Puede ser usado por las aplicaciones
como prefijo preferido.
El resto de las marcas son uri, display-name, small-icon,
large-icon, description, validator, listener. Luego puede
haber una o más marcas tag.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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,
por ejemplo SQL.
empty No tiene cuerpo.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 estático o no (true
o false).
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags sin cuerpo I
javax.servlet.jsp.tagext.Tag
javax.servlet.jsp.tagext.TagSupport
Luis Fernando Llana Dı́az
JSP: Java Server Pages
1
Inicialización
setPageContext(),
setParent(), los setXXXX.
2
doStartTag() que devuelve
SKIP_BODY (si no hay
cuerpo) o
EVAL_BODY_INCLUDE.
3
doEndTag() que devuelve
EVAL_PAGE o SKIP_PAGE
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 ;
public final String getNombre () {
return nombre ;
}
public final void setNombre ( final String newNombre ) {
this . nombre = newNombre ;
}
/* áms getters y setters */
public Valor () {
super ();
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 VAL _BO DY_I NCL UDE ;
}
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo I
javax.servlet.jsp.tagext.BodyTag
javax.servlet.jsp.tagext.BodyTagSupport
1 Inicialización setPageContext(),
2
3
4
5
Luis Fernando Llana Dı́az
JSP: Java Server Pages
setParent(), los setXXXX.
doStartTag() que devuelve
SKIP_BODY (si no hay cuerpo) o
EVAL_BODY_INCLUDE,
EVAL_BODY_BUFFERED,
doInitBody(),
setBodyContent().
doAfterBody una o más veces.
Devuelve EVAL_BODY_AGAIN para
evaluar otra vez o SKIP_BODY
para finalizar.
doEndTag() que devuelve
EVAL_PAGE o SKIP_PAGE
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo II
< %@ taglib uri = " / WEB - INF / valores . tld " prefix = " valores " %>
< valores: repite ini = " 5 " fin = " 8 " >
< % if ( ibex_id == null || ibex_id . equals ( " " )) { %>
< v al or es:entrada nombre = " < %= nombre %>" url = " < %= url %>" tipo = " < %= tipo %>" / >
< % } else { %>
< v al or es:entrada nombre = " < %= nombre %>" ibex_id = " < %= ibex_id %>" url = " < %= url %>" tipo = " < %=
< % } %>
</ valore s:repite >
< 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 >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
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 ;
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo IV
public final int doAfterBody () throws JspException {
act ++;
if ( act <= fin ) {
return E V AL _ BO DY _ BU F FE RE 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 ;
}
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo V
¿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
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo VI
< valores : mysql - conexion database = " valores " host = " localhost "
user = " luis " password = " patata " >
< valores : busca ibex_id = " < %= ibex_id %>" / >
</ valores : mysql - conexion >
La etiqueta valores:mysql-conexion construye la conexión
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 ( "óExcepcin " + e . getClass (). getName ()+
" " + e . getMessage () , e );
}
return E V AL _ BO DY _ BU F FE RE D ;
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo VII
public final int doEndTag () throws JspException {
try {
BodyContent body = getBodyContent ();
body . writeOut ( pageContext . getOut ());
connection . close ();
} catch ( Exception e ) {
throw new JspException ( "óExcepcin
" + e . getClass (). getName ()+
" : " + e . getMessage () , e );
}
return EVAL_PAGE ;
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Tags con cuerpo VIII
La clase que implementa valores:mysql-conexion tiene el
getConnection(). La clase que implementa la búsqueda debe
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 + " %’" ;
Pr epa redS tat eme nt psmt = con . prepareStatement ( 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 ( "óExcepcin " + e . getClass (). getName ()+
" : " + e . getMessage () , e );
}
return EVAL_PAGE ;
}
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
JSTL Tags
http://docs.oracle.com/javaee/5/jstl/1.1/docs/
tlddocs/index.html
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Standard tag library I
< %@ taglib uri = " http :// java . sun . com / jsp / jstl / core " prefix = " c " %>
< %@ page import = " valores . Valor " %>
<! DOCTYPE HTML PUBLIC " -// W3C // DTD HTML 4.01// EN " >
< html >
< head >
< meta http - equiv = " Content - Type " content = " text / html ; charset = utf -8 " >
< title > Prueba 5 de JSPs </ title >
</ head >
< body >
< jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / >
< jsp : setProperty name = " valor " property = " * " / >
<c : choose >
<c : when test = " $ { empty valor . nombre } " >
< form action = " pr9 . jsp " method = " get " >
< label > Nombre : </ label > < input name = " nombre " value = " $ { valor . nombre } " > < br >
< label > ibex_id : </ label > < input name = " ibex_id " value = " $ { valor . ibex_id } " > < br >
< label > URL : </ label > < input name = " url " value = " $ { valor . 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 >
</ form >
</ c : when >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Standard tag library II
<c : otherwise >
< dl >
< dt > Nombre : </ dt > < dd > <a href = " <c : url value = ’ $ { valor . url } ’/ > " >
<c : out value = " $ { valor . nombre } " / > </ a > </ dd >
< dt > ID : </ dt > < dd > <c : out value = " $ { valor . ibex_id } " / > </ dd >
< dt > Tipo : </ dt > < dd > <c : out value = " $ { valor . strTipo } " / > </ dd >
</ c : otherwise >
</ c : choose >
</ body > </ html >
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Objetos implicitos (lenguage EL) I
pageContext The context for the JSP page. Provides access to
various objects including:
servletContext The context for the JSP page’s
servlet and any web components
contained in the same application.
session The session object for the client.
request The request triggering the execution of
the JSP page.
response The response returned by the JSP page.
param Maps a request parameter name to a single value.
paramValues Maps a request parameter name to an array of
values.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Objetos implicitos (lenguage EL) II
header Maps a request header name to a single value.
headerValues Maps a request header name to an array of values.
cookie Maps a cookie name to a single cookie.
initParam Maps a context initialization parameter name to a
single value.
pageScope Maps page-scoped variable names to their values.
requestScope Maps request-scoped variable names to their
values.
sessionScope Maps session-scoped variable names to their
values.
applicationScope Maps application-scoped variable names to
their values.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Core Tags I
http://docs.oracle.com/javaee/5/jstl/1.1/docs/
tlddocs/c/tld-summary.html
< %@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
catch Catches any Throwable that occurs in its body and
optionally exposes it.
choose Simple conditional tag that establishes a context for
mutually exclusive conditional operations, marked by
<when> and <otherwise>
if Simple conditional tag, which evalutes its body if the
supplied condition is true and optionally exposes a
Boolean scripting variable representing the evaluation
of this condition
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Core Tags II
import Retrieves an absolute or relative URL and exposes its
contents to either the page, a String in ’var’, or a
Reader in ’varReader’.
forEach The basic iteration tag, accepting many different
collection types and supporting subsetting and other
functionality
forTokens Iterates over tokens, separated by the supplied
delimeters
out Like
< %= ... >
, but for expressions.
otherwise Subtag of <choose> that follows <when> tags and runs only
if all of the prior conditions evaluated to ’false’
param Adds a parameter to a containing ’import’ tag’s URL.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Core Tags III
redirect Redirects to a new URL.
remove Removes a scoped variable (from a particular scope,
if specified).
set Sets the result of an expression evaluation in a ’scope’
url Creates a URL with optional query parameters.
when Subtag of <choose> that includes its body if its condition
evalutes to ’true’
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
SQL I
http://docs.oracle.com/javaee/5/jstl/1.1/docs/
tlddocs/sql/tld-summary.html
< %@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
setDataSource Creates a simple DataSource suitable only for
prototyping.
transaction Provides nested database action elements with a
shared Connection, set up to execute all statements
as one transaction.
query Executes the SQL query defined in its body or
through the sql attribute.
update Executes the SQL update defined in its body or
through the sql attribute.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
SQL II
param Sets a parameter in an SQL statement to the
specified value.
dateParam Sets a parameter in an SQL statement to the
specified java.util.Date value.
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Formato I
http://docs.oracle.com/javaee/5/jstl/1.1/docs/
tlddocs/fmt/tld-summary.html
< %@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
requestEncoding Sets the request character encoding
setLocale Stores the given locale in the locale configuration
variable
timeZone Specifies the time zone for any time formatting or
parsing actions nested in its body
setTimeZone Stores the given time zone in the time zone
configuration variable
bundle Loads a resource bundle to be used by its tag body
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid
Formato II
setBundle Loads a resource bundle and stores it in the named
scoped variable or the bundle configuration variable
message Maps key to localized message and performs
parametric replacement
param Supplies an argument for parametric replacement to
a containing ¡message¿ tag
formatNumber Formats a numeric value as a number, currency, or
percentage
parseNumber Parses the string representation of a number,
currency, or percentage
formatDate Formats a date and/or time using the supplied styles
and pattern
parseDate Parses the string representation of a date and/or time
Luis Fernando Llana Dı́az
JSP: Java Server Pages
Departamento de Sistemas Informáticos y ComputaciónUniversidad Complutense de Madrid