Definición de etiquetas:
- Archivo tld es el
archivo de definición de las etiquetas Custom Tags
- Debemos indicar las
características de etiquetas que habrá en todo mi proyecto.
- El fichero Xml es la
descripción de nuestro sitio web
- El fichero class es la
clase con la lógica java
- El fichero JSP es la
página para mostrar las etiquetas Custom tags.
- Tlibversion: Versión
de la librería
- Jspversion: Versión
del jsp
- Shortname: El nombre
del programador
- Tagclass: Nombre del
paquete, nombre de la clase
- Bodycontent: Contenido del cuerpo, si no existe contenido, se pondrá Empty
Ejemplo
de tld:
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>2.0<jspversion>
<shortname>Programeitor<shortname>
<tag>
<name>nombreetiqueta</name>
<tagclass>nombre del paquete y de la clase</tagclass>
<bodycontent>Es el contenido del cuerpo</bodycontent>
</tag>
</taglib>
EJEMPLO 1:
1.Abrimos NetBeans y creamos un nuevo proyecto Java Web llamado ProyectoCustomTags y eligiendo el servidor Apache Tomcat
2.Sobre la carpeta WEB-INF nos crearemos una nueva carpeta que llamaremos FolderTLD
3.Sobre la carpeta FolderTLD agregamos un objeto Tag Library Descriptor y lo llamaremos mensaje
NewFile > Other > Web >TagLibraryDescriptor
Escribiremos el siguiente código dentro del fichero mensaje.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>mensaje</shortname>
<tag>
<name>primera</name>
<tagclass>paquetecustomtags.PrimeraEtiqueta</tagclass>
<bodycontent>empty</bodycontent>
</tag>
</taglib>
4.Crearemos una clase llamada PrimeraEtiqueta dentro de un paquete que se llamará paquetecustomtags
Implementamos el siguiente código dentro de la clase para, posteriormente, representarlo en una página JSP:
package paquetecustomtags;
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.*;
import java.text.*;
public class PrimeraEtiqueta extends TagSupport {
@Override
public int doStartTag() throws JspTagException
{
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspTagException
{
String horaactual = this.GetHora();
try
{
JspWriter out = pageContext.getOut();
out.write("<h1>Bienvenido a mi pagina Custom Tags</h1>");
out.write("El nombre de mi clase es: ");
out.write(getClass().getName());
out.write("<br> y la hora es " + horaactual + "<p/>");
}catch (IOException ex)
{
throw new JspTagException("Excepcion al cargar el fichero TLD " +ex.toString());
}
return EVAL_PAGE;
}
private String GetHora()
{
Date horaactual;
DateFormat formato;
String cadhora;
horaactual= Calendar.getInstance().getTime();
formato= DateFormat.getTimeInstance();
cadhora=formato.format(horaactual);
return cadhora;
}
}
5.Ahora debemos irnos al descriptor de la aplicación web y seleccionamos el fichero web.xml dentro de la
carpeta WEB-INF:
Si no existe puede crearse en NewFile > Other > Web > StandardDeploymentDescriptor
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>mietiquetacustomtag</taglib-uri>
<taglib-location>/WEB-INF/FolderTLD/mensaje.tld</taglib-location>
</taglib>
</web-app>
6.Escribiremos el siguiente código en la página index.jsp para realizar la llamada a la librería Custom Tags
que hemos creado:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="mietiquetacustomtag" prefix="MiEtiqueta" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Pagina realizada con Custom Tags</h1>
<MiEtiqueta:primera/>
</body>
</html>
-------------------------------------------------------------------------------------------------------------
------------Realizar una página JSP que mostrará una tabla con los datos de los departamentos----------------
1.Creamos un nuevo proyecto Web Application llamado AplicacionCustomTags con servidor Apache Tomcat
2.Sobre la carpeta WEB-INF, nos crearemos una nueva carpeta que llamaremos EtiquetasDEPT.
4.Sobre la carpeta EtiquetasDEPT vamos a agregar un objeto Tag Library Descriptor de la carpeta Web y lo
llamaremos etiquetadepartamentos
5.Escribiremos el siguiente código dentro del fichero etiquetadepartamentos.tld:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>2.0</jspversion>
<shortname>etiquetadepartamentos</shortname>
<tag>
<name>tabladepartamentos</name>
<tagclass>paquetecustomtags.EtiquetaTablaDept</tagclass>
<bodycontent>empty</bodycontent>
</tag>
</taglib>
6.Nos crearemos una clase para poder implementar el código de la etiqueta que acabamos de realizar.
Crearemos la clase en un paquete llamado paquetecustomtags y le pondremos de nombre EtiquetaTablaDept.
Lo que debemos realizar ahora es el acceso mediante JDBC a la tabla EMP de Oracle. Para ello, debemos agregar dentro de la carpeta Libraries el conector JDBC para Oracle.
A continuación, implementaremos el código de la clase EtiquetaTablaDept
package paquetecustomtags;
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.TagSupport;
import java.util.*;
import java.text.*;
import java.sql.*;
public class EtiquetaTablaDept extends TagSupport {
@Override
public int doStartTag() throws JspTagException
{
return SKIP_BODY;
}
@Override
public int doEndTag() throws JspTagException
{
try
{
JspWriter out = pageContext.getOut();
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
Connection cn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "SYSTEM", "12345");
Statement sentencia = cn.createStatement(); //(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = sentencia.executeQuery("SELECT * FROM DEPT");
out.write("<h1>Datos de los departamentos</h1>");
String tabla = "<table border='1'>";
tabla += "<tr><th>Numero</th><th>Nombre</th><th>Localidad</th></tr>";
while (rs.next())
{
tabla += "<tr>";
tabla += "<td>"+rs.getString(1)+"</td>";
tabla += "<td>"+rs.getString(2)+"</td>";
tabla += "<td>"+rs.getString(3)+"</td>";
tabla += "</tr>";
}
tabla += "</table>";
out.write(tabla);
}catch (Exception ex)
{
throw new JspTagException("Excepcion al cargar el fichero TLD " +ex.toString());
}
return EVAL_PAGE;
}
}
Ahora debemos irnos al descriptor de la aplicación web.
Seleccionamos el fichero web.xml dentro de la carpeta WEB-INF y escribimos lo siguiente:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web
Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<taglib>
<taglib-uri>mietiquetacustomtag</taglib-uri>
<taglib-location>/WEB-INF/EtiquetasDEPT/etiquetadepartamentos.tld</taglib-location>
</taglib>
</web-app>
Ahora vamos a agregar una pagina JSP que dibujará los empleados que tenemos en la etiqueta Custom Tag.
Le daremos el nombre tabladepartamentos
Implementamos el código para dibujar los departamentos.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@taglib uri="mietiquetacustomtag" prefix="tagdept" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<tagdept:tabladepartamentos/>
</body>
</html>
No hay comentarios:
Publicar un comentario