JSP: Java Server Pages - Universidad Complutense de Madrid

4 downloads 47 Views 283KB Size Report
Apr 29, 2013 ... JSP: Java Server Pages. Luis Fernando Llana D´ıaz. Departamento de Sistemas Informáticos y Computación. Universidad Complutense de ...
JSP: Java Server Pages Luis Fernando Llana D´ıaz Departamento de Sistemas Inform´ aticos y Computaci´ on Universidad Complutense de Madrid

29 de abril de 2013

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Java Server Pages Java empotrado dentro de HTML. < %@ page pageEncoding = " utf -8 " %> < html > < body >

Hello < %=name %> < form action = " hello . jsp " > < input name = " name " / > < button > Send

Marcas espciales: < % Java code %> < %= expression %> Variable predefinida request. Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Traducci´on 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Traducci´on 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Traducci´on 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Traducci´on a servlet IV Traducci´on de la p´agina 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 ( "

Hello " ); out . print ( name ); out . write ( "

\ n " ); out . write ( " < form action =\" hello . jsp \" >\ n " ); out . write ( " < input name =\" name \"/ >\ n " ); out . write ( " < button > Send \ n " ); out . write ( " \ n " ); out . write ( " \ n " ); out . write ( " \ n " );

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Sensible al c´odigo spaghetti I < %@ page pageEncoding = " utf -8 " %> < table > < td > < %= num %> < td >x < %= i %> < td >= < %= num * i %> < %} %> < % } %> < form action = " mult1 . jsp " > < label > Number : < input size = " 2 " name = " number " > < button > Submit

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Sensible al c´odigo spaghetti II

< %@ page pageEncoding = " utf -8 " %> < table > < % } %> < form action = " mult2 . jsp " > < label > Number : < input size = " 2 " name = " number " > < button > Submit

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Directivas: < %@ directiva atributos %> < html > < body > < %@ page import = " java . util . Date " %> < %@ page import = " java . text . DateFormat " %> < %@ page import = " java . text . SimpleDateFormat " %>

Hoy es < %=df . format ( date) %>

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

Luis Fernando Llana D´ıaz JSP: Java Server Pages

%> %> %> %>

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Habichuelas Java: JavaBeans < body > < jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / > < jsp : setProperty name = " valor " property = " * " / > < form action = " pr5 . jsp " method = " get " >

< label > Nombre : < input name = " nombre " value = " < %= nombre %>" > < br > < label > ibex_id : < input name = " ibex_id " value = " < %= ibex_id %>" > < br > < label > URL : < input name = " url " value = " < %= url %>" > < br > < label > Tipo < select name = " tipo " > < option value = " < %= Valor . ACCIONES %>" > Acciones < option value = " < %= Valor . FONDOS %>" > Fondos < button type = " submit " > Enviar < % } else { %> < jsp : getProperty name = " valor " property = " datos " / > < % } %> Luis Fernando Llana D´ıaz Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid JSP: Java Server Pages

Etiquetas personalizadas I < body > < form action = " pr6 . jsp " method = " get " >

< label > Nombre : < input name = " nombre " value = " < %= nombre == null ? " " : nombre %>" > < br > < label > Ibex ID : < input name = " ibex_id " value = " < %= ibex_id == null ? " " : ibex_id %>" > < b < label > url : < input name = " url " value = " < %= url == null ? " " : url %>" > < br > < label > Tipo : < select name = " tipo " > < option value = " < %= Valor . ACCIONES %>" > Acciones < option value = " < %= Valor . FONDOS %>" > Fondos < br > < button type = " submit " > Enviar < % } else { %>

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad 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 = " < %= < % } %>

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Variables Predefinidas request El HttpServletRequest asociada con esta petici´on. response El HttpServletResponse asociada con esta petici´on. out El PrintWriter usado para mandar la salida al usuario. session El HttpSession asociada con esta petici´on. Las sesiones est´an activadas por defecto. Recordemos el m´etodo 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Sesi´on

< body >

Has accedido < %=num . intValue () % > veces a la ´ a pgina < form action = " pr7 . jsp " >

< button name = " borrarSesion " type = " submit " > Borrar ´ o Sesin

< button name = " continuarSesion " type = " submit " > Continuar ´ o Sesin

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Directivas page Atributos: import Las cl´ausulas 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´es del m´etodo getServletInfo. Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad 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˜ no 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´a lleno, si tiene el valor false se provoca una excepci´on. errorPage P´agina JSP que procesa las exceptions. isErrorPage Indica si la p´agina es de error o no. language El u ´nico valor posible el Java Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Directivas include

Incluye una p´agina en tiempo de compilaci´ on < %@ include file = " jsp / pie . jsp " %>

Pueden incluir HTML est´atico y marcas JSP.

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Acciones JSP Las acciones JSP usan sintaxis XML para controlar el comportamiento del servlent: jsp:include Incluye una p´agina en tiempo de ejecuci´on. 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´ on a otra p´agina. 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Acci´on jsp:include I < jsp : include page = " jsp / cabecera . jsp " / > < h1 >´ ı Captulo 1 < jsp : include page = " html / capitulo1 . html " < h1 >´ ı Captulo 2 < jsp : include page = " html / capitulo2 . html " < h1 >´ ı Captulo 3 < jsp : include page = " html / capitulo3 . html " < h1 >´ ı Captulo 4 < jsp : include page = " html / capitulo4 . html " < %@ include file = " jsp / pie . jsp " %>

/> /> /> />

out . write ( " \ n J s p Ru nti meLi bra ry . include ( request , response , " html / cabecera . html " , out , false ); out . write ( " \ n " ); out . write ( "

´ ı Captulo 1 " ); out . write ( " \ n " ); J s p Ru nti meLi bra ry . include ( request , response , " html / capitulo1 . html " , out , false ); out . write ( " \ n " ); out . write ( "

´ ı Captulo 2 " ); out . write ( " \ n " ); J s p Ru nti meLi bra ry . include ( request , response , " html / capitulo2 . html " , out , false ); /* Resto de la ´ o t r a d u c c i n */

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Acci´on jsp:include II

Date date = new Date (); DateFormat df = new SimpleDateFormat ( " dd ’ de ’ MMMM ’ de ’ yyyy " ); out . write ( " \ n " ); out . write ( "

" ); out . print ( df . format ( date )); out . write ( "

\ n " ); out . write ( " \ n " ); out . write ( " \ n " ); out . write ( " \ n " );

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Las habichuelas Java I Un JavaBean es un objeto de una clase cuyos m´etodos p´ ublicos 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´ aticos y Computaci´ onUniversidad 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Las habichuelas Java III public String getDatos () { StringBuffer out = new StringBuffer (); out . append ( "
\ n " ); out . append ( "
Nombre < dd > < a href =\ " " + url + " \ " >" + nombre + " " ); out . append ( "
Apellidos < dd > " + ibex_id ); out . append ( "
Tipo < dd > " +( tipo ==1? " acciones " : " fondos " )); out . append ( " \ 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´ aticos y Computaci´ onUniversidad 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 ´ambido donde vive el objeto request V´alido para el request. Valor por defecto session V´alido para la sesi´ on. application V´alido para todas p´aginas que comparten el ServletContext. class La clase que define el JavaBean type El tipo est´atico (la clase o una superclase suya). Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad 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´olo da el valor si construye el objeto. < jsp : useBean id = " myName " ... > ... < jsp : setProperty name = " myName " property = " someProperty " ... / >

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad 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´ametros del request que case con alg´ un setXXXX del JavaBean. value (Opcional) el valor que se da la propiedad. param (Opcional) el valor se toma del par´ametro de request que se indica. Si no existe tal par´ametro no se hace nada. Se pueden omitir tanto value como param, entonces el valor se toma del par´ametro del request cuyo nombre es property. Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Las habichuelas Java Invoca al m´etodo 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´ametros 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Las habichuelas Java

Acceder valores a los campos del JavaBean. < dl > < dt > Nombre < dd > ’> < jsp : getProperty name = " valor " property = " nombre " / > < dt > Ibex ID < dd > < jsp : getProperty name = " valor " property = " ibex_id " / > < dt > Tipo < dd > < jsp : getProperty name = " valor " property = " strTipo " / >

Luis Fernando Llana D´ıaz JSP: Java Server Pages

Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad Complutense de Madrid

Las habichuelas Java < body > < jsp : useBean id = " valor " scope = " request " class = " valores . Valor " / > < jsp : setProperty name = " valor " property = " * " / > < form action = " pr5 . jsp " method = " get " >

< label > Nombre : < input name = " nombre " value = " < %= nombre %>" > < br > < label > ibex_id : < input name = " ibex_id " value = " < %= ibex_id %>" > < br > < label > URL : < input name = " url " value = " < %= url %>" > < br > < label > Tipo < select name = " tipo " > < option value = " < %= Valor . ACCIONES %>" > Acciones < option value = " < %= Valor . FONDOS %>" > Fondos < button type = " submit " > Enviar < % } else { %> < jsp : getProperty name = " valor " property = " datos " / > < % } %> Luis Fernando Llana D´ıaz Departamento de Sistemas Inform´ aticos y Computaci´ onUniversidad 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´on de los servlets es Software Libre

Por qu´e no puedo hacerlo yo para mis propias aplicaciones? Por qu´e 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Taglibs definidas por el usuario

¿Qu´e hace falta? Fichero de descripci´ on 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´ aticos y Computaci´ onUniversidad Complutense de Madrid

Ficheros tld Es un fichero XML